Dynamically access image from android res folder

I have an image in res folder similar to this

enter image description here

I want to access this dynamically, like this.

holder.Viewcover.setImageDrawable(Drawable.createFromPath("R.id." + CoverimgUrl.get(position)));

CoverimgUrl is a list with two image names: book_cover , and another blank_image , this array is generated dynamically, so how can I set this image from this list

In a word, how to dynamically access a sample located in a folder with the ability to draw, and I need to get this image name from a list of arrays?

+5
source share
3 answers
Resources res = getResources();
String mDrawableName = "image_name";
int resourceId = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resourceId);
icon.setImageDrawable(drawable );
+8
source

First make CoverimgUrl a list of integers

List<Integer> CoverimgUrl =new ArrayList<Integer>();
            CoverimgUrl.add(R.drawable.book_cover);
            CoverimgUrl.add(R.drawable.blank_image);

Then

holder.Viewcover.setImageResource(CoverimgUrl.get(position));
+1

createFromPath , .

:

int id = getResources (). getIdentifier (CoverimgUrl.get (position), "id", getPackageName ()); holder.Viewcover.setImageDrawable (GetResources () getDrawable (ID).);

getIdentifier () gets the identifier from the string. When you use the "R" class, it contains static integers for identifiers. So R.id.some_name is actually an integer, which is the identifier of the resource some_name.

Once you get this integer using getIdentifier, you can use getResources (). getDrawable () to get drawable with given ID.

Let me know if this works.

+1
source

All Articles