繁体   English   中英

如何更改tablayout中选择的选项卡的颜色

[英]How to change color of tab selected in tablayout

如何更改所选标签的颜色? 我希望每个选项卡都有自己的颜色属性。 所以选择的选项卡 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>

我将它应用到 tablayout 背景

<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"
            />

下面是它当前外观的一些屏幕截图。 在此处输入图片说明

在此处输入图片说明

理想情况下,我希望每个标签都有自己单独的颜色。

怎样才能做到这一点?

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

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

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

xml中的整个tablayout如下所示

<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" />

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM