jai*_*rik 20 android textview android-theme
如何TextView以?android:textColorPrimary编程方式设置my的文本颜色?
我已经尝试了下面的代码,但它为textColorPrimary和textColorPrimaryInverse设置文本颜色始终为白色(两者都不是白色,我已通过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);
Run Code Online (Sandbox Code Playgroud)
jai*_*rik 24
最后,我使用以下代码来获取主题的主要文本颜色 -
// 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);
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
用法:
textView.setTextColor(mActivity.getColorResCompat(android.R.attr.textColorPrimary))
Run Code Online (Sandbox Code Playgroud)
您需要检查属性是否已解析为资源或颜色值.
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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
@ColorInt int color = resolveColorAttr(context, android.R.attr.textColorPrimaryInverse);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7290 次 |
| 最近记录: |