【问题标题】:How to change color of tab selected in tablayout如何更改选项卡布局中选择的选项卡的颜色
【发布时间】:2019-07-11 03:22:45
【问题描述】:

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

以下是它当前外观的一些屏幕截图。

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

如何做到这一点?

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

【问题讨论】:

    标签: android xml android-tabs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多