Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, reference things in R.drawable. using variables?

say I want to dynamically load an image file in R.drawable.* based on the value of a string

Is there a way to do this? It seems like I need to statically refer to anything in R.

like image 255
RandomUser Avatar asked Oct 29 '11 19:10

RandomUser


People also ask

How do you reference drawable Android?

In your Android/Java source code you can also refer to that same image like this: Resources res = getResources(); Drawable drawable = res. getDrawable(R.

What is v24 in Android drawable?

Classic drawable resources such as images are stored in the drawable folder. In contrast, vector drawables are stored in drawable-v24 . For this project, keep the drawable default and click OK. You should now see the New File dialog box.

Which function is used is to load a drawable image resource?

Drawable drawable = ResourcesCompat. getDrawable (res, R. drawable. myimage, null);

What is drawable resource in Android?

A Drawable resource is a general concept for a graphic which can be drawn. The simplest case is a graphical file (bitmap), which would be represented in Android via a BitmapDrawable class. Every Drawable is stored as individual files in one of the res/drawable folders.


2 Answers

Have you declared the id for the image in XML file? If you did, you can use the following method:

Let's say you have picture.png in your res/drawable folder.

In your activity, you can set your image resource in the main.xml file

<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>

In FirstActivity

//to retrieve image using id set in xml.
String imageString = "imageId"
int resID = getResources().getIdentifier(imageString , "id", "package.name");
ImageView image = (ImageView) findViewById(resID);

imageString is the dynamic name. After which you can get the identifier of the dynamic resource.

Another method, you can do this:

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );

You will be able to reference your image resource and set your ImageView to it.

like image 194
newbie Avatar answered Oct 16 '22 22:10

newbie


int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);

Try this. This should work.

like image 9
Yashwanth Kumar Avatar answered Oct 16 '22 21:10

Yashwanth Kumar