我想使用主题的attr为textView.setTextColor()
颜色。我找到了方法:
public static int getColor(int attr, Resources.Theme theme) {
TypedValue value = new TypedValue();
theme.resolveAttribute(attr, value, true);
return value.data;
}
并且它对预期的一些TextView
不起作用。例如,它适用于R.attr.colorPrimary
(文本变为红色)并且不适用于R.attr.colorPrimarySelector
(我的自定义attr)(colorPrimarySelector
是蓝色,但文本变得透明)
但如果我使用:
public static int getColor(int attr, Context context) {
TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(attr, value, true);
return ContextCompat.getColor(context, value.resourceId);
}
它工作正常。我不明白,为什么第一次为某些View或某些attr工作而不为另一种工作,以及返回值之间的区别。语境是对的。
我认为更改文本颜色的最佳解决方案是使用资源文件中的颜色。
如果你在活动:
textView.setTextColor(getResources().getColor(R.color.colorAccent));
如果你是片段:
textView.setTextColor(getContext().getResources().getColor(R.color.colorAccent));
寻找解决方案如果颜色设置为colorStateList
- 第一种方法总是返回Color.TRANSPARENT
。因此,最好的解决方案是使用第二种方法