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
?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With