2

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.

Jadarma
  • 160
  • 1
  • 1
  • 13

2 Answers2

5

android:background = "?android:colorPrimary"

amitairos
  • 2,907
  • 11
  • 50
  • 84
0

While amitairos points out how you can style your layouts to use the standard color palettes, you asked how you could programmatically switch the theme when you have multiple color palettes in different themes.

For setting the activity theme programmatically in OnCreate: activity.setTheme(R.style.FirstTheme);

But, don't take my word for it. See another SO answer: https://stackoverflow.com/a/18301723/1738090

Related further reading: https://chris.banes.me/2014/11/12/theme-vs-style/ https://developer.android.com/guide/topics/ui/themes.html

Community
  • 1
  • 1
w3bshark
  • 2,700
  • 1
  • 30
  • 40