在Android中获取当前主题的默认TextView textColor

fst*_*any 5 android themes

我正在尝试在运行时重置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.textColor
  • android.R.attr.textColorPrimary
  • android.R.attr.textColorSecondary

他们都没有努力找回正确的颜色.我还尝试用以下方法替换方法的第一行:

TypedArray themeArray = mContext.getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {attribute});
Run Code Online (Sandbox Code Playgroud)

我不想要肮脏的解决方案:

  1. 获取并存储TextView的textColor
  2. 将颜色改变为任何颜色
  3. 将其重置为先前存储的值

任何提示?

Ben*_*min 2

定义以下扩展函数(使用 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)