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.
In your Android/Java source code you can also refer to that same image like this: Resources res = getResources(); Drawable drawable = res. getDrawable(R.
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.
Drawable drawable = ResourcesCompat. getDrawable (res, R. drawable. myimage, null);
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.
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.
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);
Try this. This should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With