-2

I am currently programming my first Android app and want to use a for-loop to add items to a View. This is done by Java:

for (int i = 1; i < 27; i++){
                items.add(new Item("Wallpaper " + i, R.drawable.wallpaper1));
            }

Am I able to use the variable "i" inside the "R.drawable.wallpaper_" call? The result should be something like:

items.add(new Item("Wallpaper " + i, R.drawable.wallpaper1));
items.add(new Item("Wallpaper " + i, R.drawable.wallpaper2));
items.add(new Item("Wallpaper " + i, R.drawable.wallpaper3));

and so on.

Thanks in advance Tafelbomber

2 Answers2

3

You can use Resources.getIdentifier(...) for this, in a following way:

for (int i=0; i < 27; i++) {
    items.add(new Item("Wallpaper " + i, getResources().getIdentifier("wallpaper" + i, "drawable", getPackageName()));
}

For example, getIdentifier("wallpaper" + 20, "drawable", getPackageName()) will resolve to com.yourapp.R.drawable.drawable20.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • 1
    Instead of hard-coding the app package, it's better to use something like `getContext().getPackageName()`. That way it will work properly even if the code is in a library shared by multiple apps. – Ted Hopp Oct 30 '14 at 19:13
0

No, you can't do that, look here if you still want to access on this way using a String. A better way is using an array:

private int[] ids = new int[] {R.drawable.wallpaper1, R.drawable.wallpaper2, R.drawable.wallpaper3}

for (int i = 1; i < 27; i++){
   items.add(new Item("Wallpaper " + i, ids[i]));
}
Community
  • 1
  • 1
Andres
  • 6,080
  • 13
  • 60
  • 110