Home » Android » android – Get attr color value based on current set theme

android – Get attr color value based on current set theme

Posted by: admin June 16, 2020 Leave a comment


In my activity I’m maintaining a SuperActivity, in which I’m setting the theme.

public class SuperActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {


<!-- ImageBackround -->
<style name="Theme.MyTheme" parent="ThemeLight">
    <item name="myBgColor">@color/translucent_black</item>

Now I want to fetch this color in one of my child activity.

As mentioned in this probable answer, I wrote:

int[] attrs = new int[] { R.attr.myBgColor /* index 0 */};
TypedArray ta = ChildActivity.this.obtainStyledAttributes(attrs);
int color = ta.getColor(0, android.R.color.background_light);
String c = getString(color);

But everytime I’m getting the value of the default value of android.R.color.background_light & not of R.attr.myBgColor.

Where I’m doing wrong. Am I passing the wrong context of ChildActivity.this?

How to&Answers:

You have two possible solutions (one is what you actually have but I include both for the sake of completeness):

TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true))
  return typedValue.data;
  return Color.TRANSPARENT;


int[] attribute = new int[] { R.attr.xxx };
TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
int color = array.getColor(0, Color.TRANSPARENT);
return color;

Color.TRANSPARENT could be any other default for sure. And yes, as you suspected, the context is very important. If you keep getting the default color instead of the real one, check out what context you are passing. It took me several hours to figure it out, I tried to spare some typing and simply used getApplicationContext() but it doesn’t find the colors then…