Alex
Alex

Reputation: 847

Drawable resource using a variable

I want to use a variable instead of R.drawable.myimage because I have a database with the image's names. I get the name from the database and I want to use the drawable resource with this name.

String flagimage = "R.drawable." + myHelper.getFlagImage(5);
int resourceId = Integer.parseInt(flagimage);
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId);

Upvotes: 18

Views: 15296

Answers (2)

blessanm86
blessanm86

Reputation: 31789

You can use the name of a resource like

getIdentifier (String name, String defType, String defPackage);

getResources().getIdentifier("us","drawable","com.app");

The above function will return an integer value same as R.drawable.us.

This is how you access with resource names.

Upvotes: 40

mAndroid
mAndroid

Reputation: 5177

You can use this code to get the identifier...

 Resources res = this.getResources(); 
 int resID = res.getIdentifier(imagename, "drawable", this.getPackageName());

Upvotes: 18

Related Questions