TabLayout(仿iOS自定义segement+scrollerview)

tabIndicatorHeight 设置width(默认只能设置height)

通过反射来设置width,代码如下
实现如下:(为了支持单个item样式改变,所以设置了一个匿名函数回调)

    /***
     * 通过反射更改tablayout的线宽度
     * */
    public interface IndicatorWidthClick{
        // 回调设置 item
        void setUpChildren(int position,LinearLayout.LayoutParams params,View child);
    }
    public static void setUpIndicatorWidth(TabLayout tabLayout, IndicatorWidthClick click) {
        Class tabLayoutClass = tabLayout.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayoutClass.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        LinearLayout layout = null;
        try {
            if (tabStrip != null) {
                layout = (LinearLayout) tabStrip.get(tabLayout);
            }
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                click.setUpChildren(i,params,child);
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

使用如下:(ReflectionHelper是我写的反射的帮助类,放置反射相关)

        final int leftPading = dp2px(this, 30);
        final int rightPading = dp2px(this, 40);
        ReflectionHelper.setUpIndicatorWidth(segeView, new ReflectionHelper.IndicatorWidthClick() {
            @Override
            public void setUpChildren(int position, LinearLayout.LayoutParams params, View child) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    if (position == 0){
                        params.setMarginStart(leftPading);
                        params.setMarginEnd(rightPading);
                    }else {
                        params.setMarginStart(rightPading);
                        params.setMarginEnd(leftPading);
                    }
                }
            }
        });

TabLayout与viewpage绑定使用

        segeView.setupWithViewPager(hScrollerView);

TabLayout title的获取(viewpage的getPageTitle)

// 
@Override
    public CharSequence getPageTitle(int position) {
// 此方法返回
}

更改TabLayout的样式(标示线的颜色,标题的颜色大小,TabLayout的背景颜色)




    
    

你可能感兴趣的:(TabLayout(仿iOS自定义segement+scrollerview))