tablayout 指示器长度

ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager(),
bean.getTabShareFragmentlist(), bean.getTabBeans());
mViewPager.setOffscreenPageLimit(bean.getTabShareFragmentlist()
.size());
mViewPager.setAdapter(mAdapter);


mTabLayout.setupWithViewPager(mViewPager);

reflex(mTabLayout); //这句话就是改变指示器长度的方法


public void reflex(final TabLayout tabLayout) {
    //了解源码得知 线的宽度是根据 tabView的宽度来设置的
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            try {
                //拿到tabLayoutmTabStrip属性
                LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                int dp10 = DensityUtil.dip2px(tabLayout.getContext(), 50
                );

                for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                    View tabView = mTabStrip.getChildAt(i);

                    //拿到tabViewmTextView属性  tab的字数不固定一定用反射取mTextView
                    Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                    mTextViewField.setAccessible(true);

                    TextView mTextView = (TextView) mTextViewField.get(tabView);

                    tabView.setPadding(0, 0, 0, 0);

                    //因为我想要的效果是   字多宽线就多宽,所以测量mTextView的宽度
                    int width = 0;
                    width = mTextView.getWidth();
                    if (width == 0) {
                        mTextView.measure(0, 0);
                        width = mTextView.getMeasuredWidth();
                    }

                    //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                    params.width = width;
                    params.leftMargin = dp10;
                    params.rightMargin = dp10;
                    tabView.setLayoutParams(params);

                    tabView.invalidate();
                }

            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    });

}




你可能感兴趣的:(tablayout,study)