Home > OS >  How to change a layout background image depending on Dark/Light theme?
How to change a layout background image depending on Dark/Light theme?

Time:11-20

I've got two images. I want to do so: when user opens an app with a Light theme - the first image is being used as a background for layouts. When user opens the app with a Dark theme - the second image is being used as a background for layouts.

To solve this problem with text colors, we can just use styles.xml and colors-day/night.xml and one line of code: <item name="android:textColor">@color/textColor</item>

I've tried to the same with images and two styles files: <item name="android:background">@drawable/day</item>

But this feature applies background to each element on a screen, not only to the main layouts.

I know, that I can do it programatically by changing a background with if statements and layout.setBackgroundResource(R.drawable.day/night);

But maybe it can be done with XML as in the case of the text color?

CodePudding user response:

To solve this problem with text colors, we can just use styles.xml and colors-day/night.xml and one line of code: @color/textColor

You need to do the same thing, but instead of res/values/colors.xml, it should be done on the drawable res/drawable/day

So, you'll have a drawable & drawable-night folders in the res directory each of which should have a unique version of the day image with the same name.

They should look like in Android Studio (Android preview):

enter image description here

And normally use the the attribute name="android:background">@drawable/day</item>

  • Related