0

I want the user to select a wallpaper and I'll set it as the android wallpaper. I'm currently using this line:

myWallpaperManager.setResource(R.drawable.a1);

Problem is it's not dynamic and I want to change the chosen image to R.drawable.a2,R.drawable.a3,R.drawable.a4, etc based on the number I got. So if I have int chosenPicNum=3 I want to create the string "R.drawable.a"+3 and then call myWallpaperManager.setResource(R.drawable.a3);

But I can't do it. The error is eclipse reads it as a string and not a resource. Currently here's the closest I've gotten:

String imageResource="R.drawable.a"+chosenPicNum) ;

So imageResource in this case is String type "R.drawable.a3" but I want it to be R.drawable.a3.

Thank you for your help!!

Dvir, ambitious 20 year old :)

tshepang
  • 12,111
  • 21
  • 91
  • 136
david
  • 1,107
  • 6
  • 12
  • 21

3 Answers3

2

Use getIdentifier() like this:

public final static String PACKAGE = "..."; // insert your package name

private int getDrawable(String name) {
    return getId(name, "drawable");
}

private int getId(String name, String type) {
    return getResources().getIdentifier(name, type, PACKAGE);
}

Access the method using:

myWallpaperManager.setResource(getDrawable("a" + chosenPicNum));
0101100101
  • 5,786
  • 6
  • 31
  • 55
  • mmm it always returns 0. Here's what my print statemants gave me: value of string a is R.drawable.a2 value of R.drawable.a1 is 2130837504 value of getDrawable(a) is 0 – david Jul 30 '14 at 11:13
  • Fixed. Not supposed to pass R.drawable (getIdentifier does that). – 0101100101 Jul 30 '14 at 11:29
0

As you use resources, you already know their number and names. So use an array:

int[] ids = new int[] {R.drawable.a1, R.drawable.a2, R.drawable.a3, };

And when you have your chosenNumPic (assuming it's 0 based):

if (chosenNumPic >= 0 && chosenNumPic < ids.length) {
    myWallpaperManager.setResource(ids[chosenNumPic]);
}

Hope it helps :)

Margarita Litkevych
  • 2,086
  • 20
  • 28
0

try this

int resId = getResources().getIdentifier("your_drawable_name"), "drawable", getActivity().getPackageName());
imageview.setBackgroundResource(resId);
Sam
  • 4,046
  • 8
  • 31
  • 47