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

Getting default TextView textColor in Android for current Theme

我正在尝试在运行时重置 TextView 的 TextColor。我想将 TextView 的默认颜色设置为 @ColorInt。相信现在的Theme都知道这一点。

这是我尝试过的:

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();
    }
}

其中属性是:

None 他们努力找回正确的颜色。我还尝试将方法的第一行替换为:

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

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

  1. 获取和存储 TextView 的 textColor
  2. 将颜色更改为任何颜色
  3. 将其重置回之前存储的值

有什么提示吗?

以下代码为您提供了一个 ColorStateList,这与您要求的不完全相同,但可能也适用于您需要它的上下文:

TypedArray themeArray = theme.obtainStyledAttributes(new int[]{android.R.attr.textColorSecondary});
ColorStateList textColorSecondary = themeArray.getColorStateList(0);

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

然后按如下方式使用它:

val defaultText = context.getColorResCompat(android.R.attr.textColorPrimary)