This is my code: It's a tabLayout that I setupWith
a 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" />
But how do I set this programmatically?
app:tabBackground="@drawable/tab_color_selector"
It is really important to set this tabBackground programmatically because I want the color to change depending on the theme that the user has chose
These are what I've already tried but none of them is working:
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));
Note:
This is my tab_color_selector.xml in 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>
Try this.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With