在Android中获取当前主题下TextView的默认文本颜色

9

我试图在运行时重置TextView的TextColor。我想获取TextView的默认颜色作为@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();
    }
}

其中属性是:

  • android.R.attr.textColor
  • android.R.attr.textColorPrimary
  • android.R.attr.textColorSecondary

但它们都不能正确检索颜色。我还尝试替换该方法的第一行:

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

我不想采用以下的不太优雅的解决方案:

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

有什么提示吗?


如果需要,TextView 的默认颜色为 #666666 - V-rund Puro-hit
不确定您是否指的是存储在R.color中的颜色,例如主要文本深色等。 - José María
@JoséMaría 不,只是当前主题的默认颜色。 - fstephany
2
@vrundpurohit 我猜如果设备制造商有自定义主题,那么值可能会不同... - fstephany
2个回答

3

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

TextView使用的资源似乎是textColorSecondary,而不是textColorPrimary。 - Alvaro Rivoir
对我来说,textColorSecondary 的结果是略微带灰色的颜色,与默认的 TextView 颜色不同,后者是黑色。textColorPrimary 得到了正确的黑色结果。在 Theme 中没有明确定义文本颜色,使用了系统默认值(Android 11)。 - aruh

2
以下代码会给你一个ColorStateList,这不完全符合你的要求,但在你需要的上下文中也可能适用:
TypedArray themeArray = theme.obtainStyledAttributes(new int[]{android.R.attr.textColorSecondary});
ColorStateList textColorSecondary = themeArray.getColorStateList(0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接