I want to assign a background image to a layout according to the value that the level variable takes at each moment.
If level=1 then you must assign img_1
If level=500 then you must assign img_500 ....
int nivel=225; //Ejemplo.
lyimg = (LinearLayout) findViewById(R.id.lyimg);
//Creo mi array
final String[][] numimg = new String[500][500];
//Guardo cada una de las imagenes (serán más de 500)
for (int contador = 1; contador < 500; ++contador) {
numimg[contador][1] = "img_"+contador;
numimg[contador][2] = ""+contador;
}
//Asigno la imagen según el nivel, cualquier combinacion.
if(){lyimg.setBackgroundResource(R.drawable.numimg[nivel][1]);} // <-Esto me da error
How can I do it? There will be hundreds of combinations so it is not worth having hundreds of IFs.
Resources are handled because
Ids
they are generated in your app's resource designer. If you want to get every image id stored in your drawable folder, try the following:The variable
niveles
must have the exact value of levels, while level must be the level from which the image is to be loaded. For the algorithm to work. You must ensure that the array has the same number of elements as levels. Otherwise (if you don't find any image with that name) you should subtract from the variablenivel
.nivel - 1 - (niveles - ids.length)
or create a dictionary orHashMap
instead of aArrayList
, where theKey
is the typeString
where it will be saved"img_"+contador
and thevalue
typeint
where you will save theid
resource. Because there will only beids.length
valid amounts of images inniveles
and it is the only way to make sure that the level you want to load, is the same one that you get from your list when some of the resources are not found within thefor
.Now, I do not recommend you to upload all the amount of images that you say since they do handle a somewhat high resolution. It can bring you memory problems and you would have to use libraries like
Glide
or create an algorithm to recycle the loaded images.To place one image or another in Java you could do something like
That would be enough for it to work for you
If you have a lot of images and you don't want to use ifs / else you could use a switch