如何以编程方式将TextView
的文本颜色设置为?android:textColorPrimary
?
我已经尝试了下面的代码,但它将textColorPrimary和textColorPrimary Inverse的文本颜色设置为白色(两者都不是白色的,我已经通过XML检查过)。
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimaryInverse, typedValue, true);
int primaryColor = typedValue.data;
mTextView.setTextColor(primaryColor);
最后,我使用以下代码来获取主题的主要文本颜色 -
// Get the primary text color of the theme
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
TypedArray arr =
getActivity().obtainStyledAttributes(typedValue.data, new int[]{
android.R.attr.textColorPrimary});
int primaryColor = arr.getColor(0, -1);
您需要检查属性是否已解析为资源或颜色值。
textColorPrimary的默认值不是Color,而是ColorStateList,它是一种资源。
@ColorInt public static int resolveColorAttr(Context context, @AttrRes int colorAttr) {
TypedValue resolvedAttr = resolveThemeAttr(context, colorAttr);
// resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color
int colorRes = resolvedAttr.resourceId != 0 ? resolvedAttr.resourceId : resolvedAttr.data;
return ContextCompat.getColor(context, colorRes);
}
public static TypedValue resolveThemeAttr(Context context, @AttrRes int attrRes) {
Theme theme = context.getTheme();
TypedValue typedValue = new TypedValue();
theme.resolveAttribute(attrRes, typedValue, true);
return typedValue;
}
用法:
@ColorInt int color = resolveColorAttr(context, android.R.attr.textColorPrimaryInverse);
kotlin中的扩展版本
@ColorInt
fun Context.getColorResCompat(@AttrRes id: Int): Int {
val resolvedAttr = TypedValue()
this.theme.resolveAttribute(id, resolvedAttr, true)
val colorRes = resolvedAttr.run { if (resourceId != 0) resourceId else data }
return ContextCompat.getColor(this, colorRes)
}
用法:
textView.setTextColor(mActivity.getColorResCompat(android.R.attr.textColorPrimary))