首页 > 解决方案 > 以编程方式更改 ColorDrawable 选定状态颜色/ Tablayout 背景颜色

问题描述

我有一个 tab_color_selector.xml 可绘制对象,我在 TabLayout 中使用它。

我想在 onTabSelected 上更改它的选定状态颜色。

tab_color_selector.xml

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

表格布局 xml:

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/c_white"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabIndicatorColor="@color/summary_blue"
        app:tabIndicatorHeight="5px"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/c_white"
        app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
        app:tabTextColor="@color/c_white" />

在这里,我想以编程方式更改 ColorDrawable android:state_selected="true" 颜色。

  tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {


            switch (tab.getPosition()) {
                case 0:
                                            ((ColorDrawable)tabLayout.getBackground()).setColor(getResources().getColor(R.color.material_yellow400));

                    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.color_17));
                    break;

                case 1:
                                            ((ColorDrawable)tabLayout.getBackground()).setColor(getResources().getColor(R.color.material_pink400));
                    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.out_pat_green));
                    break;


            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

我尝试了 setColor() 和 setColorFilter() 以及 setBackground()

标签: colorstabsbackground-colorandroid-tablayoutcolordrawable

解决方案


创建样式并将其作为标签添加到 TabLayout 小部件中


推荐阅读