Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Variable passed for R.drawable.variableValue

Tags:

android

    iv.setImageResource(R.drawable.icon);

this line is working good for me

can I pass a variable value instead of icon like if i have 10 images in drawable and i want to decide on runtime which image to show can i pass the value through a variable and work it like

    String variableValue = imageName;
    iv.setImageResource(R.drawable.variableValue);
like image 619
A Khan Avatar asked Apr 22 '11 22:04

A Khan


2 Answers

Resources.getIdentifier() can solve your problem.

String variableValue = imageName;
iv.setImageResource(getResources().getIdentifier(variableValue, "drawable", getPackageName()));
like image 174
iForests Avatar answered Nov 09 '22 22:11

iForests


You could use an array to define your drawables:

int[] images = new int[2];
images[0] = R.drawables.image1;
images[1] = R.drawables.image2;

And then you can use this array to set a image at runtime:

lv.setImageResource(images[i]);

Where is is in this case either 0 to point to the first image or 1 to point to the second image of the array.

like image 32
RoflcoptrException Avatar answered Nov 09 '22 22:11

RoflcoptrException