I have imported some images as a drawable, using Android Studios Resource Manager.
It will be used in an Jetpack Compose Android app as a background image. It works as expected in night- and day-mode.
But there is a section in the app, where users can select from a list of these backgrounds. The list should show a preview of each background in both day- and night-mode.
Like this:
When i display the image, i am doing it so:
Image(painter = painterResource(id = R.drawable.my_image))
So i am always getting the image for the currently selected mode. But i want to explicitly request the dark and light variants of the image to display them side-by-side.
I imagined something like this:
Image(painter = painterResource(id = R.drawable.my_image, isDark = false))
Image(painter = painterResource(id = R.drawable.my_image, isDark = true))
I am aware that this API does not exist. But how can i achieve retrieving an image that is not meant for the current context?
It seems like this is not possible. An easy workaround in your case would be to provide seperate drawables for showing the two backgrounds next to each other.
I am assuming that your current folder structure looks like this:
drawable
background.jpg [1]
drawable-night
background.jpg [2]
Now copy the drawble-night/background.jpg
file to the drawable
folder and rename it. Do the same thing for the drawable/background.jpg
file:
drawable
background.jpg [1]
background-light.jpg [copy of 1]
background-dark.jpg [copy of 2]
drawable-night
background.jpg [2]
Now, you can explicitly reference these files in your code like so:
Image(painter = painterResource(id = R.drawable.background-light))
Image(painter = painterResource(id = R.drawable.background-dark))
As Android does not find any background-light.jpg
and background-dark.jpg
in a drawable-night
folder, it will always pick these images from the drawable
folder, no matter whether dark mode is enabled or not.
The logic in which Android determines which resources to load is provided in the official documentation.