How can I dynamically change the image of an ImageView using the name of the image?
Suppose I have a blue_yellow button, a black_white button and a default button; At the same time I have an image with different backgrounds in the drawable folder:
- manzana_blue_yellow
- apple_black_white
- manzana_default
After pressing a button I need to load the image the respective one. That is, if I press the black_white button, the imageview should show the image called apple_black_white if I press the default button it will show apple_default .
This is actually for several images that I have in an ImageView ArrayList, all the images have their respective prefix of the color that is repeated.
The logic that I have in mind would be to obtain the name of the image (Ej: manzana_black_white) and until the first underscore is the name of the image, then the color that is currently set continues; once obtained the name of the image by string manipulation apple _ add the string of the color I need _blue_yellow thus getting the name of the image I need apple_blue_yellow strong> and thereby search for the resource with that name in order to set it in the Respective ImageView.
My array with all the imageview reaches the constructor of the class
val imgs: ArrayList<ImageView>?
The function I want to use to change the images
fun changeImage(color:String){
when(color){
"blue_yellow" -> {
if (imgs != null) {
for (img in imgs){
/*Acá deberia cambiar la imagen actual por la con prefijo blue_yellow*/
}
}
}
"black_white" -> {
if (imgs != null) {
for (img in imgs){
/*Acá deberia cambiar la imagen actual por la con prefijo black_white*/
}
}
}
"white_black" -> {
if (imgs != null) {
for (img in imgs){
/*Acá deberia cambiar la imagen actual por la con prefijo white_black*/
}
}
}
"default" -> {
if (imgs != null) {
for (img in imgs){
/*Acá deberia cambiar la imagen actual por la con prefijo default*/
}
}
}
}
}
The idea is that by clicking on the button I can call this function and pass the prefix, thereby changing all the respective images within the ImageView