Reputation: 34016
I want to provide different app themes for my users to choose from. Each theme would have two variables Color1 and Color2 and my idea is to reference these colors in the activies xml.
Something like:
<style name="Theme.LightTheme" parent="Theme.General">
<item name="android:color1">#000000</item>
<item name="android:color2">#ffffff</item>
</style>
And then in an activity xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:color1"
android:background="?android:color2" />
So when the theme is changed the colors in the activities change.
How can this be done?
Upvotes: 1
Views: 920
Reputation: 38605
You can define your own attributes. Most people do this in res/values/attrs.xml
:
<resources>
<attr name="color1" format="color" />
<attr name="color1" format="color" />
</resources>
Then in your style, you can refer to the attribute you created (note there's no android:
prefix):
<style name="Theme.LightTheme" parent="Theme.General">
<item name="color1">#000000</item>
<item name="color2">#ffffff</item>
</style>
Now in your layout XML files, you refer to the attribute value of the current theme (again, note the lack of android:
prefix):
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/color1"
android:background="?attr/color2" />
Upvotes: 3