You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TabLayout中为不同标签设置不同的文本颜色

app:tabTextColor是TabLayout提供的全局统一配置项,会把所有tab的文字颜色改成同一个值,没法满足单个tab自定义颜色的需求,你可以用以下两种方案实现:

方案1:动态遍历Tab修改颜色

Tab添加完成后直接遍历所有Tab,拿到对应位置Tab的文字控件单独设置颜色即可,代码示例:

Kotlin 示例

// 遍历所有Tab
for (i in 0 until tabLayout.tabCount) {
    val tab = tabLayout.getTabAt(i) ?: continue
    // 获取Tab内的TextView控件,不同版本TabLayout索引可能有差异,可调试确认实际索引
    val tabText = tab.view.getChildAt(1) as TextView
    // 按Tab位置对应设置颜色
    when(i) {
        1 -> tabText.setTextColor(Color.BLUE) // 位置从0开始计数,标签b是第2个Tab对应i=1
        2 -> tabText.setTextColor(Color.parseColor("#FF9800")) // 橙色
        3 -> tabText.setTextColor(Color.parseColor("#9C27B0")) // 紫色
        4 -> tabText.setTextColor(Color.RED)
    }
}

Java 示例

for (int i = 0; i < tabLayout.getTabCount(); i++) {
    TabLayout.Tab tab = tabLayout.getTabAt(i);
    if (tab == null) continue;
    TextView tabText = (TextView) tab.view.getChildAt(1);
    switch (i) {
        case 1:
            tabText.setTextColor(Color.BLUE);
            break;
        case 2:
            tabText.setTextColor(Color.parseColor("#FF9800"));
            break;
        case 3:
            tabText.setTextColor(Color.parseColor("#9C27B0"));
            break;
        case 4:
            tabText.setTextColor(Color.RED);
            break;
    }
}

方案2:自定义Tab布局实现(扩展性更强)

如果后续还需要修改Tab的字体大小、图标、边距等其他样式,推荐直接自定义Tab布局:

  1. 先创建自定义Tab布局layout/custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tab_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="14sp"/>
  1. 添加Tab时绑定自定义布局并设置对应颜色:
// 标签b
val tabB = tabLayout.newTab().setCustomView(R.layout.custom_tab)
(tabB.customView?.findViewById<TextView>(R.id.tab_title))?.apply {
    text = "b"
    setTextColor(Color.BLUE)
}
tabLayout.addTab(tabB)

// 标签c
val tabC = tabLayout.newTab().setCustomView(R.layout.custom_tab)
(tabC.customView?.findViewById<TextView>(R.id.tab_title))?.apply {
    text = "c"
    setTextColor(Color.parseColor("#FF9800"))
}
tabLayout.addTab(tabC)

// 剩余标签d、e同理设置对应颜色即可

注意:如果TabLayout绑定了ViewPager/ViewPager2,需要在Tab选中监听或者页面切换监听里同步处理选中/未选中状态的颜色,避免切换页面后自定义颜色被全局样式覆盖。

内容的提问来源于stack exchange,提问作者sooyeon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:15:03