简体   繁体   中英

Setting an ImageView from the drawable folder dynamicly

Hello developers out there,

I have written a class called Item. Now I want this "Item" to get an image in the constructor from the drawable folder. I already tried to somehow get the resourceId from the images in the drawable folder, but didn't know how, because there is now such function as imageView.getResourceId() which isn't the best solution anyway because I would need to temporarly add all images from drawable to an imageView and then get the Id. Is there any way to solve this problem?

Thank you for your help

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

Solution:

Just use this code in java to set the drawable image to ImageView dynamically:

your_image_view_object.setImageDrawable(ContextCompat.getDrawable(Your_Activity.this, R.drawable.your_drawable_image));

For Example:

imageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_profilepic));

That's it. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM