这是我的代码:它是一个TabLayout,我使用setupWith
一个Viewpager
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
app:tabPaddingEnd="-1dp"
app:tabBackground="@drawable/tab_color_selector"
app:tabPaddingStart="-1dp"
app:tabTextAppearance="@style/MineCustomTabText" />
但是我该如何以编程的方式设置它呢?
app:tabBackground="@drawable/tab_color_selector"
编程设置选项卡的背景色非常重要,因为我想让颜色根据用户选择的主题而变化。
以下是我已经尝试过的方法,但都不起作用:
tabLayout.setBackground(getResources().getDrawable(R.drawable.tab_color_selector));
tabLayout.setBackgroundResource((R.drawable.tab_color_selector));
tabLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_color_selector));
tabLayout.setBackground(ContextCompat.getDrawable(this, R.drawable.tab_color_selector));
注意:
这是我的tab_color_selector.xml文件,在drawable目录下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white" android:state_selected="true" />
<item android:drawable="@color/blue_alu" />
</selector>