TabFlowLayout 可以通过设置 SelectorDrawable 实现颜色渐变的指示条。

具体步骤如下:

  1. 在 drawable 文件夹下创建一个新的 xml 文件,例如 'tab_indicator.xml',用于设置 SelectorDrawable。

示例代码:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#FF00FF"
                android:endColor="#00FF00"
                android:type="linear"
                android:angle="0"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
        </shape>
    </item>
</selector>

该 SelectorDrawable 包含两个状态:选中状态和未选中状态。选中状态下使用渐变色,未选中状态下使用白色。

  1. 在 TabFlowLayout 中设置 SelectorDrawable。

示例代码:

tabFlowLayout.setTabIndicatorSelector(R.drawable.tab_indicator);
  1. 运行程序并查看效果。

完整示例代码:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill"
    app:tabIndicatorHeight="4dp"
    app:tabIndicatorGravity="bottom"
    app:tabIndicatorFullWidth="false"
    app:tabTextColor="#666666"
    app:tabSelectedTextColor="#FF0000"
    app:tabBackground="@android:color/white"/>

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabFlowLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill"
    app:tabIndicatorHeight="4dp"
    app:tabIndicatorGravity="bottom"
    app:tabIndicatorFullWidth="false"
    app:tabTextColor="#666666"
    app:tabSelectedTextColor="#FF0000"
    app:tabBackground="@android:color/white"/>
TabLayout tabLayout = findViewById(R.id.tabLayout);
TabLayout.Tab tab1 = tabLayout.newTab().setText("Tab 1");
TabLayout.Tab tab2 = tabLayout.newTab().setText("Tab 2");
tabLayout.addTab(tab1);
tabLayout.addTab(tab2);

TabFlowLayout tabFlowLayout = findViewById(R.id.tabFlowLayout);
tabFlowLayout.addTab(new TabFlowLayout.Tab().setText("Tab 1"));
tabFlowLayout.addTab(new TabFlowLayout.Tab().setText("Tab 2"));
tabFlowLayout.setTabIndicatorSelector(R.drawable.tab_indicator);

效果如下图所示:

image

Android TabFlowLayout 指示条颜色渐变配置教程

原文地址: https://www.cveoy.top/t/topic/oU0b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录