Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attr color value based on current set theme

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

public class SuperActivity extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MyTheme);
    }
}

themes.xml

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

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);
ta.recycle();

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?

like image 338
collin Avatar asked Apr 27 '14 07:04

collin


1 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;
else
  return Color.TRANSPARENT;

or

int[] attribute = new int[] { R.attr.xxx };
TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
int color = array.getColor(0, Color.TRANSPARENT);
array.recycle();
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...

like image 97
Gábor Avatar answered Sep 30 '22 18:09

Gábor