Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get colors from current app theme from within layout.xml?

I've made an app using only one theme, but now I want the user to be able to change it during runtime. As some layout elements need to be colored using a specific color, all my layout.xml-s have proprieties like android:background="@color/colorBackground" or something of the sort.

Currently, I have made a color pallete inside the colors.xml. It looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#607D8B</color>
    <color name="colorPrimaryDark">#455A64</color>
    <color name="colorAccent">#FF9800</color>
    <color name="colorBackground">#FAFAFA</color>
    <color name="colorTextSubtitle">#F0F0F0</color>
    <color name="colorTextSubtitleBackground">#AA000000</color>
</resources>

However, this way I can only have one theme. I was thinking about doing something like having the colors be part of a theme style (all themes will have the same color items, but with different values).

How can I make it so my layout files detect the apps current theme and get that color name from there? So something like android:background="[currentTheme.colorBackground]" so that I can have multiple styles and then changing between them.

I thought about putting the themes in shared prefferences or something similar and then programatically changing the colors when overriding the onCreate() method, but that seems overly complicated and I thought there must be an easier way. However I cannot find anything on the sort online.

like image 236
Jadarma Avatar asked Dec 09 '25 04:12

Jadarma


1 Answers

android:background = "?android:colorPrimary"

like image 171
amitairos Avatar answered Dec 10 '25 17:12

amitairos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!