以编程方式更改ColorDrawable所选状态颜色/ Tablayout背景颜色

时间:2019-01-03 11:23:23

标签: colors tabs background-color android-tablayout colordrawable

我有一个可绘制的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>

Tablayout 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()

1 个答案:

答案 0 :(得分:0)

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