这是我的代码:这是一个 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"
以编程方式设置此 tabBackground 非常重要,因为我希望颜色根据用户选择的主题而改变
这些是我已经尝试过的方法,但没有一个起作用:
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));
注意:
这是我在 drawable 中的 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/white" android:state_selected="true" />
<item android:drawable="@color/blue_alu" />
</selector>
最佳答案
试试这个。
ViewGroup tabStrip = (ViewGroup) tabLayout.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
View tabView = tabStrip.getChildAt(i);
if (tabView != null) {
int paddingStart = tabView.getPaddingStart();
int paddingTop = tabView.getPaddingTop();
int paddingEnd = tabView.getPaddingEnd();
int paddingBottom = tabView.getPaddingBottom();
ViewCompat.setBackground(tabView, AppCompatResources.getDrawable(tabView.getContext(), tabViewBgResId));
ViewCompat.setPaddingRelative(tabView, paddingStart, paddingTop, paddingEnd, paddingBottom);
}
}
关于android - 如何设置应用:tabBackground of a tabLayout programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535394/