首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TabLayout切换时不更改项目颜色

TabLayout切换时不更改项目颜色
EN

Stack Overflow用户
提问于 2020-03-23 00:42:55
回答 2查看 283关注 0票数 0

我有一个带有图标的tabLayout,选定的选项卡将图标突出显示为红色,但另一个选项卡的图标也显示为红色,并且我希望在切换到该选项卡时更改该图标的颜色,而这两个图标始终为红色

代码语言:javascript
复制
 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

代码语言:javascript
复制
<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" />
EN

回答 2

Stack Overflow用户

发布于 2020-03-23 01:03:08

在可绘制文件夹中创建bg_tab.xml文件。

代码语言:javascript
复制
<?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属性设置可绘制

代码语言:javascript
复制
<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" />
票数 0
EN

Stack Overflow用户

发布于 2020-03-23 02:25:56

解决了这个问题

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60802051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档