我正在尝试在运行时重置TextView的TextColor.我想将TextView的默认颜色作为a @ColorInt.我相信当前的主题知道这一点.
这是我试过的:
public @ColorInt int getDefaultThemeColor(int attribute) {
TypedArray themeArray = mContext.getTheme().obtainStyledAttributes(new int[] {attribute});
try {
int index = 0;
int defaultColourValue = 0;
return themeArray.getColor(index, defaultColourValue);
}
finally {
themeArray.recycle();
}
}
Run Code Online (Sandbox Code Playgroud)
其中属性是:
android.R.attr.textColorandroid.R.attr.textColorPrimaryandroid.R.attr.textColorSecondary他们都没有努力找回正确的颜色.我还尝试用以下方法替换方法的第一行:
TypedArray themeArray = mContext.getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {attribute});
Run Code Online (Sandbox Code Playgroud)
我不想要肮脏的解决方案:
任何提示?
定义以下扩展函数(使用 kotlin):
@ColorInt
@SuppressLint("ResourceAsColor")
fun Context.getColorResCompat(@AttrRes id: Int): Int {
val resolvedAttr = TypedValue()
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)
然后按如下方式使用它:
val defaultText = context.getColorResCompat(android.R.attr.textColorPrimary)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1087 次 |
| 最近记录: |