I've got the following problem. I want to write a random generator, which provides me a random image from R.id.drawable ... So I made a random generator and it now it is choosing a random string. But the problem is: I can't draw it, because I have to provide the R.id.drawable.xxxx as an integer variable and not as string. Because this is a name of an integer, I cannot convert it with Integer.Parse();
Is there any solution or does somebody know a way how to choose a random integer? Thanks in advance.
- 4,259
 - 1
 - 30
 - 41
 
- 75
 - 8
 
4 Answers
Put all of the drawable values in an array drawables. Then generate a random value value between 0 and drawables.length, and access it by drawables[value].
Also, I think you mean:
R.drawable.xxxx
Instead of:
R.id.drawable.xxxx
- 3,342
 - 4
 - 34
 - 51
 
Note that variable names are only available at compile time, not run-time. This means that you need to find a completely different solution to your problem.
One possibility is a switch statement. Let's say you have 2 images. You can do something like this:
int imageId = -1;
switch(Math.Random(2)) {
    case 1:
        imageId = R.drawable.image1;
        break;
    case 2:
        imageId = R.drawabel.image2;
        break;
}
- 81,660
 - 23
 - 145
 - 268
 
Consider this example R file.
public static final class id {
    public static final int s1=0x7f050000;
    public static final int s10=0x7f050009;
    public static final int s11=0x7f05000a;
    public static final int s12=0x7f05000b;
    public static final int s13=0x7f05000c;
    public static final int s14=0x7f05000d;
    public static final int s15=0x7f05000e;
    public static final int s16=0x7f05000f;
    public static final int s2=0x7f050001;
    public static final int s3=0x7f050002;
    public static final int s4=0x7f050003;
    public static final int s5=0x7f050004;
    public static final int s6=0x7f050005;
    public static final int s7=0x7f050006;
    public static final int s8=0x7f050007;
    public static final int s9=0x7f050008;
}
Then try to navigate using the following code..
import java.lang.reflect.Field;
/* ... */
 for (int i = 1; i < 16; i++) {
int id = R.id.class.getField("s" + i).getInt(0);
 //do something here
 }
Select one random using your own logic.
refer this question How do I iterate through the id properties of R.java class?
You can also get the identifier using that string.
For example, to get the integer value of R.drawable.ic_launcher with only the string name of it, you can do this:
getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
- 2,822
 - 1
 - 31
 - 41