fstephany
fstephany

Reputation: 2354

Getting default TextView textColor in Android for current Theme

I'm trying to reset the TextColor of a TextView at runtime. I would like to get the default color for TextView as a @ColorInt. I believe that the current Theme knows this.

Here's what I tried:

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

where attribute is:

None of them worked to retrieve the right color. I've also tried to replace the first line of the method with:

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

I don't want the dirty solution of:

  1. getting and storing the textColor of a TextView
  2. changing the color to whatever
  3. Reset it back to the previously stored value

Any hint?

Upvotes: 9

Views: 3975

Answers (2)

Benjamin
Benjamin

Reputation: 7368

Define the following extension function (using 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)
}

And then use it as follow:

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

Upvotes: 2

mtotschnig
mtotschnig

Reputation: 1481

The following code gives you a ColorStateList, which is not exactly what you asked for, but might be also applicable in the context where you need it:

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

Upvotes: 1

Related Questions