Android TabLayout.SetTabTextColor()在尝试更改文本颜色时不工作
我有一个工作的TabLayout,我试图在更改选项卡时动态更新选项卡文本颜色。为此,我在我的TabLayout上调用Android TabLayout.SetTabTextColor()在尝试更改文本颜色时不工作,android,android-support-library,android-design-library,android-tablayout,Android,Android Support Library,Android Design Library,Android Tablayout,我有一个工作的TabLayout,我试图在更改选项卡时动态更新选项卡文本颜色。为此,我在我的TabLayout上调用setTabTextColors()方法,如下所示: tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { tabLayout.setTabT
setTabTextColors()
方法,如下所示:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tabLayout.setTabTextColors(newColorStateList);
}
(...)
});
由于某些原因,文本颜色不会更新。有人知道如何动态更新选项卡文本颜色吗
我正在使用设计支持库v22.2.0。经过一番调查,似乎TableOut中的文本视图在创建后没有更新颜色 我想出的解决方案是浏览TabLayout的儿童视图,并直接更新他们的颜色
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);
}
}
}
它最终在设计支持库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();
}
}
...
}
另外,确保不要使用单独的xml文件来设置选项卡的样式。类似这样的东西,如我所拥有的(custom_tab.xml):
TabLayout
有这样一种方法-
setTabTextColors(int normalColor, int selectedColor)
记住,int
不是颜色资源值,而是从十六进制解析的int
例:
“记住,int不是颜色资源值,而是从十六进制解析的int”这非常有用,谢谢
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText(R.string.tab_response);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_bar_icon_response, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
setTabTextColors(int normalColor, int selectedColor)
tabLayout.setTabTextColors(Color.parseColor("#D3D3D3"),Color.parseColor("#2196f3"))