TabLayout自定义总结

1、常用属性

<android.support.design.widget.TabLayout
	android:id="@+id/tabLayout2"
	android:layout_width="match_parent"
	android:layout_height="30dp"
	app:tabBackground="@color/transparent"
	app:tabIndicator="@drawable/kd_enet_indicator_14"
	app:tabIndicatorColor="@color/kd_enet_cl_3F78DF"
	app:tabIndicatorFullWidth="false"
	app:tabIndicatorHeight="3dp"
	app:tabMode="scrollable"
	app:tabRippleColor="@android:color/transparent"
	app:tabSelectedTextColor="@color/kd_enet_cl_333"
	app:tabTextAppearance="@style/kd_enet_TabLayoutTextStyle"
	app:tabTextColor="@color/kd_enet_cl_666" />

1、app:tabMode="scrollable"属性:

能实现滑动均分,当导航不足一屏的时候,去掉app:tabMode="scrollable"才能实现均分展示.

2、取消选中水波纹效果:

app:tabRippleColor=“@android:color/transparent”

3、改变整个TabLayout的背景色:
app:tabBackground=“@color/blue”

4、修改TabItem 字体大小:
app:tabTextAppearance=“@style/kd_enet_TabLayoutTextStyle”

<style name="kd_enet_TabLayoutTextStyle">
    <item name="android:textSize">16sp</item>
    <!--        <item name="android:textStyle">bold</item>-->
</style>

5、圆角指示器:

<?xml version="1.0" encoding="utf-8"?>
<!--在 API 23 以上,支持直接在 layer-list 里给 <item> 标签设置宽度和高度:-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="@dimen/dp_40"
        android:height="@dimen/dp_4"
        android:gravity="center_horizontal">
        <shape>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

参考:官方文档:

2、文字选中加粗

1、效果:
在这里插入图片描述

2、自定义TabItem 布局:kd_enet_tab_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tab_item_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/kd_enet_cl_666"
        android:textSize="16sp" />

</LinearLayout>

3、代码控制选中字体的样式(粗细、颜色等)

private void initTab1() {
    String[] mTitles1 = {
            "业务应用", "指挥调度", "技术赋能"};

    TabLayout mTabLayout1 = nViewDataBinding.tabLayout1;

    //TabLayout的基本使用
    for (int i = 0; i < mTitles1.length; i++) {
        TabLayout.Tab tab = mTabLayout1.newTab();
        tab.setText(mTitles1[i]);//这里一定要设置,否则不显示
        tab.setCustomView(getTabView(i, mTitles1));//使用自定义Item布局
        mTabLayout1.addTab(tab);
    }
    //初始值默认选中
    updateTabTextView(mTabLayout1.getTabAt(mTabLayout1.getSelectedTabPosition()),
            true, R.color.kd_enet_cl_3F78DF, R.color.kd_enet_cl_333);

    mTabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            updateTabTextView(tab, true, R.color.kd_enet_cl_3F78DF, R.color.kd_enet_cl_333);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            updateTabTextView(tab, false, R.color.kd_enet_cl_3F78DF, R.color.kd_enet_cl_333);
        }

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

/**
* 使用自定义的Item布局
*/    
private View getTabView(int currentPosition, String[] strings) {
    View view = LayoutInflater.from(getContext()).inflate(R.layout.kd_enet_tab_item, null);
    TextView textView = view.findViewById(R.id.tab_item_textview);
    textView.setText(strings[currentPosition]);
    return view;
}

/**
* 每次选择更新Item样式
*/
private void updateTabTextView(TabLayout.Tab tab, boolean isSelect, int textSelectColor, int textUnSelectColor) {
    if (isSelect) {
        //选中加粗
        TextView tabSelect = tab.getCustomView().findViewById(R.id.tab_item_textview);
        tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
        tabSelect.setTextColor(ContextCompat.getColor(getContext(), textSelectColor));//颜色
        tabSelect.setText(tab.getText());
    } else {
        TextView tabUnSelect = tab.getCustomView().findViewById(R.id.tab_item_textview);
        tabUnSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        tabUnSelect.setTextColor(ContextCompat.getColor(getContext(), textUnSelectColor));
        tabUnSelect.setText(tab.getText());
    }
}

注意:如果使用自定义布局,xml中文字相关的设置就不会生效了:

//这些样式设置不会生效了
app:tabSelectedTextColor="@color/kd_enet_cl_3F78DF"
app:tabTextColor="@color/kd_enet_cl_333" 

参考:TabLayout选中加粗

3、自定义指示器样式

1、效果图:
图1

2、需求:圆角指示器,控制宽高:

3、自定义样式:R.drawable.kd_enet_indicator_14.xml

<?xml version="1.0" encoding="utf-8"?><!--https://blog.csdn.net/u013719138/article/details/89964674-->
<!--在 API 23 以上,支持直接在 layer-list 里给 <item> 标签设置宽度和高度:-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="14dp"
        android:height="3dp"
        android:gravity="center_horizontal">
        <shape>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

4、使用:

app:tabIndicator="@drawable/kd_enet_indicator_14"

4、自定义Tab样式

参考:TabLayout使用自定义的图文布局,每个Tab设置不同的背景

在这里插入图片描述
1、需求:TabLayout每个Tab选中背景不一样:左侧圆角、中间方块、右侧圆角。

2、页面布局:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/cl_F2">
  <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/cl_check_statistic"
        android:layout_marginStart="16dp"
        android:layout_marginTop="13dp"
        android:layout_marginEnd="16dp"
        app:tabIndicatorHeight="0dp"
        app:tabRippleColor="@color/bg_transparent" />

    <View
        android:id="@+id/divider_line"
        android:layout_width="match_parent"
        android:layout_height="0.33dp"
        android:layout_below="@id/tablayout"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:background="@color/cl_ccc" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/divider_line"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp" />
</RelativeLayout>

3、代码控制每个Item的样式:

private final String[] titleArr = {"待完成", "待提交", "主动检查"};
private final int[] selectedArr = {R.drawable.icon_pending_selected, R.drawable.icon_uncommit_selected, R.drawable.icon_initiative_check_selected};
private final int[] unSelectedArr = {R.drawable.icon_pending_unselected, R.drawable.icon_uncommit_unselected, R.drawable.icon_initiative_check_unselected};
private TabLayout.OnTabSelectedListener onTabSelectedListener;

/**
* 导航栏布局:https://blog.csdn.net/xiaoshuxgh/article/details/80389570
 */
private void initLayout() {
    myFragment = new ArrayList<>();
    myFragment.add(new PendingFragment());
    myFragment.add(new UnCommitFragment());
    myFragment.add(new InitiativeCheckFragment());

    nViewDataBinding.viewpager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return myFragment.get(i);
        }

        @Override
        public int getCount() {
            return myFragment.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titleArr[position];
        }
    });

    nViewDataBinding.viewpager.setOffscreenPageLimit(2);
    nViewDataBinding.tablayout.setupWithViewPager(nViewDataBinding.viewpager);

    // 注意:这个方法需要放在setupWithViewPager()后面
    for (int i = 0; i < nViewDataBinding.tablayout.getTabCount(); i++) {
        TabLayout.Tab tabView = nViewDataBinding.tablayout.getTabAt(i);
        tabView.setCustomView(getTabView(i));
        setTabBackground(tabView, false);
    }

    onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            //设置选中图标样式
            View tabView = tab.getCustomView();
            if (tabView == null) {
                LegoLog.d("tabView is null");
                return;
            }
            tabView.findViewById(R.id.tabicon).setBackgroundResource(selectedArr[tab.getPosition()]);

            //设置选中字体颜色
            TextView textView = tabView.findViewById(R.id.tabtext);
            textView.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_color));
            setTabBackground(tab, true);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            //设置未选中图标样式
            View tabView = tab.getCustomView();
            if (tabView == null) {
                LegoLog.d("tabView is null");
                return;
            }
            tabView.findViewById(R.id.tabicon).setBackgroundResource(unSelectedArr[tab.getPosition()]);

            //设置未选中字体颜色
            TextView textView = tabView.findViewById(R.id.tabtext);
            textView.setTextColor(ContextCompat.getColor(getContext(), R.color.cl_666));
            setTabBackground(tab, false);
        }

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

    nViewDataBinding.tablayout.addOnTabSelectedListener(onTabSelectedListener);
    setTabBackground(nViewDataBinding.tablayout.getTabAt(DEFAULT_POSITION), true);
}
    
/**
 * 使用自定义的View布局
 *
 * @param position
 * @return
 */
private View getTabView(int position) {
    View v = LayoutInflater.from(getContext()).inflate(R.layout.icon_view, null);
    ImageView iv = v.findViewById(R.id.tabicon);
    TextView tv = v.findViewById(R.id.tabtext);

    tv.setText(titleArr[position]);
    //设置默认页面
    if (position == DEFAULT_POSITION) {
        iv.setBackgroundResource(selectedArr[position]);
        tv.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_color));
    } else {
        iv.setBackgroundResource(unSelectedArr[position]);
        tv.setTextColor(ContextCompat.getColor(getContext(), R.color.cl_666));
    }
    return v;
}

/**
 * TabLayout每个Tab选中背景不一样。
 * https://blog.csdn.net/qq_32606467/article/details/103068611
 *
 * @param tab
 * @param selected
 */
private void setTabBackground(TabLayout.Tab tab, boolean selected) {
    Drawable drawable = null;
    switch (tab.getPosition()) {
        case 0:
            if (selected) {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_selected_0);
            } else {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_unselected_0);
            }
            break;
        case 1:
            if (selected) {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_selected_1);
            } else {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_unselected_1);
            }
            break;
        case 2:
            if (selected) {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_selected_2);
            } else {
                drawable = ContextCompat.getDrawable(getContext(), R.drawable.tab_background_unselected_2);
            }
            break;
    }

    ViewCompat.setBackground(tab.view, drawable);
}

5、动态修改Tab的标题

如果TabLayout 已经加载完成,这时候想修改某个Tab的标题;

5.1、使用的是原生的Tab:

nViewDataBinding.tabTodo.getTab(0).setText("");

5.2、修改自定义Tab的标题-1:

如果使用setCustomView(),设置了自定义的Tab;这个时候使用getTab(0).setText(“”);不会生效;

 List<String> titleList = new ArrayList<>();
 titleList.add("今日");
 titleList.add("本周");
 titleList.add("本月");
 titleList.add("本季");
 //TabLayout的基本使用
 for (int i = 0; i < titleList.size(); i++) {
     TabLayout.Tab tab = nViewDataBinding.tabTodo.newTab();
     tab.setText(titleList.get(i));
     tab.setCustomView(getTodoTabView(titleList.get(i), 14));
     nViewDataBinding.tabTodo.addTab(tab);
 }

需要通过getCustomView()获取到自定义的View,再进行值的修改:

TextView textView= nViewDataBinding.tabTodo.getTabAt(index).getCustomView().findViewById(R.id.tab_item_textview);
textView.setText(title + numStr);

5.3、修改自定义Tab的标题-2:

  • 先removeAllTabs();
  • 再重新添加Tab();
// 初始化Layout
List<String> titleList = new ArrayList<>();
titleList.add("今日");
titleList.add("本周");
titleList.add("本月");
titleList.add("本季");
//TabLayout的基本使用
for (int i = 0; i < titleList.size(); i++) {
    TabLayout.Tab tab = nViewDataBinding.tabTodo.newTab();
    tab.setText(titleList.get(i));
    tab.setCustomView(getTodoTabView(titleList.get(i), 14));
    nViewDataBinding.tabTodo.addTab(tab);
}
int selPosition = nViewDataBinding.tabTodo.getSelectedTabPosition();
nViewDataBinding.tabTodo.removeAllTabs();//1、先移除所有Tab
for (TodoCountResult result : todoCountResults) {
        String type = result.getType();
        String title = "";
        if ("today".equalsIgnoreCase(type)) {
            title = "今日";
        } else if ("week".equalsIgnoreCase(type)) {
            title = "本周";
        } else if ("month".equalsIgnoreCase(type)) {
            title = "本月";
        } else if ("quarter".equalsIgnoreCase(type)) {
            title = "本季";
        } else {
            LegoLog.d("未知的类型:" + type);
        }

        TabLayout.Tab tab = nViewDataBinding.tabTodo.newTab();
        tab.setText(title + numStr);// 设置新的标题
        tab.setCustomView(getTodoTabView(title + numStr, 14));
        nViewDataBinding.tabTodo.addTab(tab);//2、再重新添加Tab
   }
  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Tab的标题如何修改?有哪些方法可以修改Tab的标题? 回答:要修改TabLayout中Tab的标题,可以使用以下几种方法。如果使用的是原生的Tab,可以通过`nViewDataBinding.tabTodo.getTab(0).setText("");`来修改指定Tab的标题。\[1\]如果使用了自定义Tab,使用`tab.setText("新标题")`来修改Tab的标题是无效的。在这种情况下,可以通过设置自定义的View来实现修改标题。首先,创建一个包含标题的List,然后使用循环为每个Tab设置标题和自定义View,如下所示: ``` List<String> titleList = new ArrayList<>(); titleList.add("今日"); titleList.add("本周"); titleList.add("本月"); titleList.add("本季"); for (int i = 0; i < titleList.size(); i++) { TabLayout.Tab tab = nViewDataBinding.tabTodo.newTab(); tab.setText(titleList.get(i)); tab.setCustomView(getTodoTabView(titleList.get(i), 14)); nViewDataBinding.tabTodo.addTab(tab); } ``` 这样就可以通过设置自定义View的方式修改Tab的标题了。\[2\]另外,如果想修改TabItem的字体大小,可以使用`app:tabTextAppearance="@style/kd_enet_TabLayoutTextStyle"`来设置样式,然后在样式中设置字体大小,如下所示: ``` <style name="kd_enet_TabLayoutTextStyle"> <item name="android:textSize">16sp</item> <!--<item name="android:textStyle">bold</item>--> </style> ``` 通过设置样式中的`android:textSize`属性,可以修改TabItem的字体大小。\[3\] #### 引用[.reference_title] - *1* *2* *3* [TabLayout自定义总结](https://blog.csdn.net/zhijiandedaima/article/details/113363708)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值