Tablayout 指示器宽度问题

11 篇文章 0 订阅
开发中常遇到要设置指示器的宽度,默认的指示器宽度是均分屏幕宽度。

如何设置指示器的宽度,统一为某一个值呢?


自定义TabLayout

布局中引用

 <baoming.view.EnhanceTabLayout
        android:id="@+id/enhance_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/color_dark_theme"
        app:tabIndicatorHeight="2dp"
        app:tabIndicatorWidth="30dp"
        app:tabSelectTextColor="@color/color_dark_theme"
        app:tabTextColor="@color/black"
        app:tabTextSize="14"
        app:tab_Mode="mode_fixed" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tab_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="首页"
        android:textColor="#333333"
        android:textSize="14sp" />

    <View
        android:id="@+id/tab_item_indicator"
        android:layout_width="30dp"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:background="@color/colorPrimary"
        android:visibility="invisible" />
</RelativeLayout>

自定义属性:attrs.xml中

<!--TabLayout:自定义宽度-->
    <declare-styleable name="EnhanceTabLayout">
        <attr name="tab_Mode" format="enum">
            <enum name="mode_fixed" value="1" />
            <enum name="mode_scrollable" value="2" />
        </attr>
        <attr name="tabIndicatorColor" format="color" />
        <attr name="tabSelectTextColor" format="color" />
        <attr name="tabTextColor" format="color" />
        <attr name="tabIndicatorHeight" format="dimension" />
        <attr name="tabIndicatorWidth" format="dimension" />
        <attr name="tabTextSize" format="integer" />
    </declare-styleable>

这里tabTextSize设置为integer,是因为字体大小统一用int表示,设置进去的时候指定Sp.

/**
 *  对 support Design 包中的TabLayout包装
 *  主要实现功能:更改indicator 的长度
 * Created on 2018/5/18.
 */

public class EnhanceTabLayout extends FrameLayout {
    private TabLayout mTabLayout;
    private List<String> mTabList;
    private List<View> mCustomViewList;
    private int mSelectIndicatorColor;
    private int mSelectTextColor;
    private int mUnSelectTextColor;
    private int mIndicatorHeight;
    private int mIndicatorWidth;
    private int mTabMode;
    private int mTabTextSize;

    public EnhanceTabLayout(@NonNull Context context) {
        super(context);
        init(context,null);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    private void readAttr(Context context,AttributeSet attrs){
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.EnhanceTabLayout);
        mSelectIndicatorColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabIndicatorColor,context.getResources().getColor(R.color.colorAccent));
        mUnSelectTextColor =  typedArray.getColor(R.styleable.EnhanceTabLayout_tabTextColor, Color.parseColor("#666666"));
        mSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabSelectTextColor,context.getResources().getColor(R.color.colorAccent));
        mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorHeight,1);
        mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorWidth,0);
        mTabTextSize = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabTextSize,13);
        mTabMode = typedArray.getInt(R.styleable.EnhanceTabLayout_tab_Mode,2);
        typedArray.recycle();
    }

    private void init(Context context,AttributeSet attrs){
        readAttr(context,attrs);

        mTabList = new ArrayList<>();
        mCustomViewList = new ArrayList<>();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.enhance_tab_layout,this,true);
        mTabLayout = view.findViewById(R.id.enhance_tab_view);

        // 添加属性
        mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED:TabLayout.MODE_SCROLLABLE);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // onTabItemSelected(tab.getPosition());
                // Tab 选中之后,改变各个Tab的状态
                for (int i=0;i<mTabLayout.getTabCount();i++){
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    if(view == null){
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if(i == tab.getPosition()){ // 选中状态
                        text.setTextColor(mSelectTextColor);
                        indicator.setBackgroundColor(mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    }else{// 未选中状态
                        text.setTextColor(mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public List<View> getCustomViewList(){
        return mCustomViewList;
    }

    public void addOnTabSelectedListener (TabLayout.OnTabSelectedListener onTabSelectedListener){
        mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
    }

    /**
     * 与TabLayout 联动
     * @param viewPager
     */
    public void setupWithViewPager(@Nullable ViewPager viewPager) {
        mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager,this));
    }




    /**
     * retrive TabLayout Instance
     * @return
     */
    public TabLayout getTabLayout(){
        return mTabLayout;
    }

    /**
     * 添加tab
     * @param tab
     */
    public void addTab(String tab){
        mTabList.add(tab);
        View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

    public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener{

        private final ViewPager mViewPager;
        private final WeakReference<EnhanceTabLayout> mTabLayoutRef;

        public ViewPagerOnTabSelectedListener(ViewPager viewPager,EnhanceTabLayout enhanceTabLayout) {
            mViewPager = viewPager;
            mTabLayoutRef = new WeakReference<EnhanceTabLayout>(enhanceTabLayout);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
            if(mTabLayoutRef!=null){
                List<View> customViewList = mTabLayout.getCustomViewList();
                if(customViewList == null || customViewList.size() ==0){
                    return;
                }
                for (int i=0;i<customViewList.size();i++){
                    View view = customViewList.get(i);
                    if(view == null){
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if(i == tab.getPosition()){ // 选中状态
                        text.setTextColor(mTabLayout.mSelectTextColor);
                        indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    }else{// 未选中状态
                        text.setTextColor(mTabLayout.mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
        TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
        if(indicatorWidth>0){
            View indicator = view.findViewById(R.id.tab_item_indicator);
            ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
            layoutParams.width  = indicatorWidth;
            layoutParams.height = indicatorHeight;
            indicator.setLayoutParams(layoutParams);
        }
        tabText.setTextSize(textSize);
        tabText.setText(text);
        return view;
    }

Activity代码中:

 for(int i=0;i<sTitle.length;i++){
            mEnhanceTabLayout.addTab(sTitle[i]);
        }
mViewPager.setAdapter(adapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
mEnhanceTabLayout.setupWithViewPager(mViewPager);
注意,如果是配合ViewPager使用,需要下面两行代码,单独使用则不需要:

mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
mEnhanceTabLayout.setupWithViewPager(mViewPager);
tabText.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);

替换tabText.setTextSize( textSize);


参考 https://mp.weixin.qq.com/s/5n6GpWAaWECvFOT0_HLXhw


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 Android TabLayout 的指示器颜色设置为渐变色,可以执行以下步骤: 1. 定义渐变色 在 drawable 目录下创建一个 gradient.xml 文件,定义渐变色。例如: ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="@color/colorStart" android:endColor="@color/colorEnd" android:angle="0" /> </shape> ``` 其中,@color/colorStart 和 @color/colorEnd 分别指定渐变色的起始和结束颜色,android:angle 表示渐变的角度。 2. 设置 TabLayout 的指示器颜色 通过 TabLayout.setSelectedTabIndicatorColor() 方法设置 TabLayout 的指示器颜色。这里将渐变色作为指示器的颜色: ``` TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.transparent)); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setColor(ContextCompat.getColor(this, R.color.transparent)); gradientDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT); gradientDrawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT); gradientDrawable.setColors(new int[]{ ContextCompat.getColor(this, R.color.colorStart), ContextCompat.getColor(this, R.color.colorEnd) }); tabLayout.setSelectedTabIndicator(gradientDrawable); ``` 其中,tabLayout.setSelectedTabIndicatorColor() 方法设置指示器的颜色为透明,防止出现默认的颜色叠加在渐变色上的情况。然后创建一个 GradientDrawable 对象,设置渐变色的起始和结束颜色,以及渐变的方向。最后调用 tabLayout.setSelectedTabIndicator() 方法将渐变色作为指示器的背景。 3. 设置 TabLayout 的指示器高度 通过 TabLayout.setSelectedTabIndicatorHeight() 方法设置 TabLayout 的指示器高度。例如: ``` tabLayout.setSelectedTabIndicatorHeight(getResources().getDimensionPixelSize(R.dimen.indicator_height)); ``` 其中,R.dimen.indicator_height 是在 dimens.xml 文件中定义的指示器高度的值。 这样,就可以将 Android TabLayout 的指示器颜色设置为渐变色,并且可以设置指示器的高度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值