You can do this using attributes. First define your attribute in attrs.xml
(this file goes under the 'values' folder):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="myCoolColor" format="color" />
</resources>
Then in your styles.xml
, define myCoolColor
for each theme:
<style name="Theme.MyApp" parent="@style/Theme.Light">
<item name="myCoolColor">#123456</item>
</style>
<style name="Theme.MyApp.Dark" parent="@style/Theme.Dark">
<item name="myCoolColor">#654321</item>
</style>
Now, specify myCoolColor
as the background of your view:
android:background="?myCoolColor"
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):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="myCoolColor" format="color|reference" />
</resources>
Change your styles.xml
to reference a color for each theme:
<style name="Theme.MyApp" parent="@style/Theme.Light">
<item name="myCoolColor">@color/blue</item>
</style>
<style name="Theme.MyApp.Dark" parent="@style/Theme.Dark">
<item name="myCoolColor">@color/green</item>
</style>
Finally define the colors in your colors.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="blue">#0000FF</color>
<color name="green">#00FF00</color>
</resources>
That's it!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…