Android

ReflexUtil

2021-01-04  本文已影响0人  明日未期

修改tabLayout宽度适用androidx

public class ReflexUtil {
    public static void tabIndicatorWidth(final TabLayout tab) {
        tab.post(new Runnable(){

                @Override
                public void run() {
                    try {
                        LinearLayout tabStrip= (LinearLayout) tab.getChildAt(0);
                        for (int i=0; i < tabStrip.getChildCount();i++) {
                            View tabView=tabStrip.getChildAt(i);
                            Field textViewField= tabView.getClass().getDeclaredField("textView");
                            textViewField.setAccessible(true);
                            TextView textView= (TextView) textViewField.get(tabView);
                            tabView.setPadding(0, 0, 0, 0);
                            int width=0;
                            width = textView.getWidth();
                            if (width == 0) {
                                textView.measure(0, 0);
                                width = textView.getMeasuredWidth();
                            }
                            
                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                            int margin=DisplayUtil.dp2px(tabView.getContext(), 8);
                            params.width = width;
                            params.leftMargin = margin;
                            params.rightMargin = margin;

                            tabView.setLayoutParams(params);
                            tabView.invalidate();
                        }
                    } catch (Exception e) {
                        LogUtil.d(e.getMessage());
                    }
                }
            });
    }
}
上一篇下一篇

猜你喜欢

热点阅读