130

I am generating a string from database dynamically which has the same name of image in drawable folder.

Now I want to set that value for ImageView using setImageDrawable(R.id.StringGenerated) dynamically.

Any Suggestions..

HaveNoDisplayName
  • 7,711
  • 106
  • 32
  • 44
Arun
  • 1,367
  • 2
  • 9
  • 10

17 Answers17

204

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);
King RV
  • 3,680
  • 1
  • 13
  • 16
  • Thanks a ton..i found it somewhere else bt still thanks for your Efforts.. :) – Arun Jan 04 '12 at 06:33
  • 12
    However using setImageResource() "does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup ... consider using setImageDrawable() or setImageBitmap()." _(Android documentation)_ – chetto Oct 25 '12 at 18:30
  • 6
    You could also get the id by simply using: R.drawable.filemane – Artur Nov 15 '13 at 05:41
106
Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
            ImageView imgView = new ImageView(context);
            imgView = (ImageView)findViewById(R.id.image1);
            imgView.setImageDrawable(image);

or

setImageDrawable(getResources().getDrawable(R.drawable.icon));
NikhilReddy
  • 6,734
  • 10
  • 34
  • 55
  • he said he is generating a string from database dynamically with the same name of image. – Paresh Mayani Dec 27 '11 at 09:14
  • 3
    getDrawable(R.drawable.icon) is deprecated – Daryn Sep 29 '16 at 03:41
  • For people who need to resolve getDrawable(R.drawable.icon) is deprecated, try to read this [SO link](https://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22) – Codingpan Feb 27 '18 at 19:52
82

I personally prefer to use the method setImageResource() like this.

ImageView myImageView = (ImageView)findViewById(R.id.myImage);
myImageView.setImageResource(R.drawable.icon);
jlopez
  • 6,141
  • 2
  • 47
  • 89
  • 1
    this one wins since you may want to change image from any place in your code where you do not have context to call getResources() method on it. e.g in Adapters. No need to pass context through constructor just for this funcionality. – Phatee P Dec 22 '16 at 00:30
  • 1
    way cleaner. I dont get why this is not the preferred answer. – Benjamin Basmaci Nov 22 '18 at 14:00
  • 1
    @BenjaminBasmaci This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead. (From Android Documentation) – Tayyab Mazhar May 01 '20 at 11:15
25

The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources class to resolve the string into that integer.

Resources res = getResources();
int resourceId = res.getIdentifier(
   generatedString, "drawable", getPackageName() );
imageView.setImageResource( resourceId );

This resolves your generated string into the integer that the ImageView can use to load the right image.

Alternately, you can use the id to load the Drawable manually and then set the image using that drawable instead of the resource ID.

Drawable drawable = res.getDrawable( resourceId );
imageView.setImageDrawable( drawable );
Greyson
  • 3,430
  • 1
  • 19
  • 22
13

As simple as this answer:

Drawable myDrawable = getResources().getDrawable(R.drawable.pic);
imageview.setImageDrawable(myDrawable);
TylerH
  • 19,065
  • 49
  • 65
  • 86
Ahmad Arslan
  • 4,732
  • 6
  • 39
  • 58
12

All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

ContextCompat.getDrawable(mContext, drawable)

From documented method

public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id

portfoliobuilder
  • 6,488
  • 10
  • 63
  • 119
12

You can try to use this code:

ImageView ImgView = (ImageView)findViewById(R.id.ImgView);
ImgView.setImageResource(R.drawable.myicon);
Gilles Heinesch
  • 2,284
  • 1
  • 14
  • 33
Mersad Nilchy
  • 543
  • 3
  • 17
9

This works, at least in Android API 15

ImageView = imgv;
Resources res = getResources(); // need this to fetch the drawable
Drawable draw = res.getDrawable( R.drawable.image_name_in_drawable );
imgv.setImageDrawable(draw);

You could use setImageResource(), but the documentation specifies that "does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup ... consider using setImageDrawable() or setImageBitmap()." as stated by chetto

resmall
  • 630
  • 1
  • 6
  • 10
5

imageView.setImageDrawable(getResources().getDrawable(R.drawable.my_drawable));

lxknvlk
  • 2,230
  • 20
  • 28
4

If You cannot get Resources object like this in a class which is not an Activity, you have to add getContext() method for getResources() for example

ImageView image = (ImageView) v.findViewById(R.id.item_image);
int id = getContext().getResources().getIdentifier(imageName, "drawable", getContext().getPackageName());
image.setImageResource(id);
TylerH
  • 19,065
  • 49
  • 65
  • 86
Vladimir Salguero
  • 4,156
  • 2
  • 30
  • 39
3

You can also use something like:

imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(), R.drawable.generatedID));

or using Picasso:

Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);

ninjahoahong
  • 2,384
  • 19
  • 20
1

From API 22 use:

Drawable myDrawable =  ResourcesCompat.getDrawable(getResources(), 
                        R.drawable.dos_red, null);
Arghya Sadhu
  • 28,262
  • 9
  • 35
  • 59
Oras
  • 82
  • 8
0

I had the same problem as you and I did the following to solve it:

**IMAGEVIEW**.setImageResource(getActivity()
             .getResources()
             .getIdentifier("**IMG**", "drawable", getActivity()
             .getPackageName()));
bitoiu
  • 5,698
  • 5
  • 33
  • 50
JCDecary
  • 497
  • 1
  • 6
  • 18
0

Construct a POJO.java class and create "constructor, getter & setter methods"

class POJO{
        public POJO(Drawable proImagePath) {
                setProductImagePath(proImagePath);
        }

        public Drawable getProductImagePath() {
                return productImagePath;
        }

        public void setProductImagePath(Drawable productImagePath) {
                this.productImagePath = productImagePath;
        }
}

Then setup the adapters through image drawable resources to CustomAdapter.java

    class CustomAdapter extends ArrayAdapter<POJO>{

       private ArrayList<POJO> cartList = new ArrayList<POJO>();
       public MyCartAdapter(Context context, int resource) {
          super(context, resource);
       }

       public MyCartAdapter(Context context, ArrayList<POJO> cartList) {
          super(context, 0, cartList);
          this.context = context;
          this.cartList = cartList;

       }

       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
          /*
          *Here you can setup your layout and references.
          **/
          ImageView productImage = (ImageView) rootView.findViewById(R.id.cart_pro_image);
          productImage.setImageDrawable(POJO.getProductImagePath());
        }
    }

Then pass the references through ActivityClass.java

public class MyCartActivity extends AppCompatActivity{
       POJO pojo;
       CustomAdapter customAdapter;
       ArrayList<POJO> cartList = new ArrayList<POJO>();

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.your_layout);

          customAdapter = new CustomAdapter(this, cartList);

          pojo = new POJO(getResources().getDrawable(R.drawable.help_green));

    }
}
Abdul Gaffar
  • 561
  • 2
  • 7
  • 16
-3

a piece of my project, everything works! )

@Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final ModelSystemTraining modelSystemTraining = items.get(position);

int icon = context.getResources().getIdentifier(String.valueOf(modelSystemTraining.getItemIcon()), "drawable", context.getPackageName());

        final FragmentViewHolderSystem fragmentViewHolderSystem = (FragmentViewHolderSystem) holder;
        final View itemView = fragmentViewHolderSystem.itemView;
//                Set Icon
fragmentViewHolderSystem.trainingIconImage.setImageResource(icon);
//                Set Title
fragmentViewHolderSystem.title.setText(modelSystemTraining.getItemTitle());
//                Set Desc
fragmentViewHolderSystem.description.setText(modelSystemTraining.getItemDescription());
  • You should really add some explanation as to why this code should work - you can also add comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question. – ishmaelMakitla Jun 16 '16 at 14:05
-3

btnImg.SetImageDrawable(GetDrawable(Resource.Drawable.button_round_green));

API 23 Android 6.0

isaac
  • 1
-4

The 'R' file can not be generated at the run time of the app. You may use some other alternatives such as using if-else or switch-case

Vinod Maurya
  • 3,957
  • 10
  • 47
  • 79
  • This doesn't seem to relate to the question. It seems as though he's trying to set an imageview to an already existing resource, rather than trying to generate `R` again – Greyson Dec 27 '11 at 22:46