如何更改在TabLayout中选择的标签的颜色

时间:2019-07-11 03:22:45

标签: android xml android-tabs

如何更改所选标签的颜色?我希望每个标签都具有自己的颜色属性。因此,选择的选项卡1将为红色。选项卡2将选择为蓝色。选项卡3选择为黄色。未选中时,它们将返回到标签的原始颜色。

当前,我正在使用选择器来更改所选标签的背景。但是,这仅允许一种颜色。我想有多种颜色

这是unselected_tab.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid
        android:color="@color/colorPrimaryDark" />

</shape>

这是selected_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid
        android:color="@color/tabSelectedColor" />

</shape>

这是我正在使用的选择器

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="50"
    android:exitFadeDuration="50" >

    <item android:drawable="@drawable/tab_selected"
        android:state_selected="false" />
    <item android:drawable="@drawable/tab_unselected"
        android:state_selected="true"/>
</selector>

我将其应用到布局背景

<com.google.android.material.tabs.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimaryDark"
            android:minHeight="?attr/actionBarSize"
            android:elevation="5dp"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:tabIndicatorColor="@android:color/white"
            app:tabMode="scrollable"
            app:tabMaxWidth="100dp"
            app:tabBackground="@drawable/tab_selector"
            />

下面是一些有关当前外观的屏幕截图。 enter image description here

enter image description here

理想情况下,我希望每个选项卡都有其自己的单独颜色。

如何做到这一点?

编辑:理想情况下,我希望可以通过编程方式更改每个选项卡的颜色

2 个答案:

答案 0 :(得分:0)

只需在标签页布局中添加以下2个属性即可。

app:tabSelectedTextColor="@color/color_primary_text"
app:tabTextColor="@color/color_secondary_text"

xml中的整个标签布局如下所示

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_gravity="bottom"
android:background="@color/button_background"
android:fillViewport="true"
app:tabBackground="@drawable/fixed_bottom_button"
app:tabIndicatorColor="@color/color_primary_text"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/color_primary_text"
app:tabTextColor="@color/color_secondary_text" />

答案 1 :(得分:0)

对于正在寻求解决方案的任何人。我找到了一个。您可以将颜色应用于tabLayout的子项的布局。对于某些参考代码,这是我使用的非常有效的方法

final LinearLayout tabsContainerLayout = (LinearLayout)expenseTabs.getChildAt(0);
Linear LayouttempLinearLayout = (LinearLayout)tabsContainerLayout.getChildAt(selectedTabPosition);
tempLinearLayout.setBackgroundColor(Color.RED);
相关问题