I’m pretty sure that this question already has been answered somewhere. It just seems too common. But I can’t find the answer. I can’t also figure out the solution.
Here’s the problem:
I want one of my TableRow’s to have different background color. It’s simple, I just need to add
android:background="#123456"
In TableRow’s XML Declaration. But, I also want my application to have two themes. In the other theme, the TableRow should have different background color. I just can’t find a way to define a color value inside a theme and use it. I would like to type something like this:
<style name="Theme.MyApp" parent="@style/Theme.Light">
<color "my_cool_color">#123456</color>
</style>
<style name="Theme.MyApp.Dark" parent="@style/Theme.Dark">
<color "my_cool_color">#654321</color>
</style>
And, in TableRow’s declaration:
android:background="@color/my_cool_color"
So, when I change the theme, the color of that one TableRow’s background also changes. I’ve tried in many ways for many hours and didn’t succeed… One thing I didn’t try, was creating my own widget basing on TableRow and declaring a separate style for it – I think this should work, but it’s just too heavy solution for so simple problem.
You can do this using attributes. First define your attribute in
attrs.xml(this file goes under the ‘values’ folder):Then in your
styles.xml, definemyCoolColorfor each theme:Now, specify
myCoolColoras the background of your view:You can go further and use a reference to a color so you can keep your colors defined in one place. Change the attribute to include a reference (note that we can use a color OR a reference):
Change your
styles.xmlto reference a color for each theme:Finally define the colors in your
colors.xml:That’s it!