【问题标题】:TabLayout not changing item color when switchingTabLayout在切换时不改变项目颜色
【发布时间】:2020-03-23 02:25:55
【问题描述】:

我有一个带有图标的 tabLayout,所选选项卡将图标突出显示为红色,但另一个选项卡的图标也为红色,我想在切换到该选项卡时更改该图标颜色,而不是两个图标一直是红色的

 val tabLayoutMediator = TabLayoutMediator(tabLayout, viewPager2,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->

                when (position) {
                    0 -> {
                        tab.text = "tab1"
                        tab.icon = ContextCompat.getDrawable(requireContext(),R.drawable.ic_fork)

                    }
                    1 -> {
                        tab.text = "tab2"
                        tab.icon = ContextCompat.getDrawable(requireContext(),R.drawable.ic_basket)
                    }
                }

            })
        tabLayoutMediator.attach()

XML

<com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabInlineLabel="true"
            app:tabSelectedTextColor="@color/red" />

【问题讨论】:

    标签: android kotlin android-tablayout android-architecture-navigation


    【解决方案1】:

    在drawable文件夹中创建bg_tab.xml文件。

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@android:color/red" android:state_selected="true"/>
        <item android:drawable="@android:color/white" android:state_selected="false"/>
    </selector>
    

    并使用 tabBackground 属性设置可绘制对象

    <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabBackground="@drawable/bg_tab"
                app:tabInlineLabel="true"
                app:tabSelectedTextColor="@color/red" />
    

    【讨论】:

    • 这会改变整个标签的背景,而不仅仅是图标
    【解决方案2】:

    解决了
    <android.support.design.widget.TabLayout
         android:id="@+id/tab_layout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:tabIconTint="@color/your_color_selector"
         app:tabIndicatorColor="@color/selected_color"/>
    
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/selected_color" android:state_selected="true"/>
        <item android:color="@color/unselected_color"/>
    </selector>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      相关资源
      最近更新 更多