Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting default TextView textColor in Android for current Theme

Tags:

android

themes

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:

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

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?

like image 940
fstephany Avatar asked May 19 '16 12:05

fstephany


2 Answers

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)
like image 107
Benjamin Avatar answered Nov 16 '22 09:11

Benjamin


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);
like image 23
mtotschnig Avatar answered Nov 16 '22 09:11

mtotschnig