TabLayout.setTabTextColors() not working when trying to change text color
It's finally fixed in Design Support Library 22.2.1.
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tabLayout.setTabTextColors(getResources().getColor(R.color.normal), getResources().getColor(R.color.selected));
try {
// FIXME: 20.7.2015 WORKAROUND: https://code.google.com/p/android/issues/detail?id=175182 change indicator color
Field field = TabLayout.class.getDeclaredField("mTabStrip");
field.setAccessible(true);
Object value = field.get(tabLayout);
Method method = value.getClass().getDeclaredMethod("setSelectedIndicatorColor", Integer.TYPE);
method.setAccessible(true);
method.invoke(value, getResources().getColor(R.color.selected));
} catch (Exception e) {
e.printStackTrace();
}
}
...
}
TabLayout
has a method like this -
setTabTextColors(int normalColor, int selectedColor)
Remember, that int
is not color resource value but int
parsed from hex
Ex:
tabLayout.setTabTextColors(Color.parseColor("#D3D3D3"),Color.parseColor("#2196f3"))
After a bit of investigation, it seems like the textviews inside the TabLayout just don't get their colors updated after their creation.
The solution I came up with was to go through the children views of the TabLayout and update their colors directly.
public static void setChildTextViewsColor(ViewGroup viewGroup, ColorStateList colorStateList) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
setChildTextViewsColor((ViewGroup) child, colorStateList);
} else if (child instanceof TextView) {
TextView textView = (TextView) child;
textView.setTextColor(colorStateList);
}
}
}
Then, in the OnTabSelectedListener:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
setChildTextViewsColor(tabLayout, newColorStateList);
}
(...)
});