Using setImageDrawable dynamically to set image in an ImageView

AndroidAndroid Widget

Android Problem Overview


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..

Android Solutions


Solution 1 - Android

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 2 - Android

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));

Solution 3 - Android

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

ImageView myImageView = (ImageView)findViewById(R.id.myImage);
myImageView.setImageResource(R.drawable.icon);

Solution 4 - Android

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 );

Solution 5 - Android

As simple as this answer:

Drawable myDrawable = getResources().getDrawable(R.drawable.pic);
imageview.setImageDrawable(myDrawable);

Solution 6 - Android

You can try to use this code:

ImageView ImgView = (ImageView)findViewById(R.id.ImgView);
ImgView.setImageResource(R.drawable.myicon);

Solution 7 - Android

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

Solution 8 - Android

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

Solution 9 - Android

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

Solution 10 - Android

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);

Solution 11 - Android

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);

Solution 12 - Android

From API 22 use:

Drawable myDrawable =  ResourcesCompat.getDrawable(getResources(), 
                        R.drawable.dos_red, null);

Solution 13 - Android

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

**IMAGEVIEW**.setImageResource(getActivity()
             .getResources()
             .getIdentifier("**IMG**", "drawable", getActivity()
             .getPackageName()));

Solution 14 - Android

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));
  
    }
}

Solution 15 - Android

Now you can use setImageDrawable(Drawable drawable). example:

ImageView iState = findViewById(R.id.imageview_state);
if (isOk){
    iState.setImageDrawable(getDrawable(R.drawable.outline_ok));
}else{
    iState.setImageDrawable(getDrawable(R.drawable.outline_no));
}

enter image description here

Solution 16 - Android

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());

Solution 17 - Android

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

API 23 Android 6.0

Solution 18 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArunView Question on Stackoverflow
Solution 1 - AndroidKing RVView Answer on Stackoverflow
Solution 2 - AndroidNikhilReddyView Answer on Stackoverflow
Solution 3 - AndroidjlopezView Answer on Stackoverflow
Solution 4 - AndroidGreysonView Answer on Stackoverflow
Solution 5 - AndroidAhmad ArslanView Answer on Stackoverflow
Solution 6 - AndroidMersad NilchyView Answer on Stackoverflow
Solution 7 - AndroidportfoliobuilderView Answer on Stackoverflow
Solution 8 - AndroidresmallView Answer on Stackoverflow
Solution 9 - AndroidlxknvlkView Answer on Stackoverflow
Solution 10 - AndroidVladimir SalgueroView Answer on Stackoverflow
Solution 11 - AndroidninjahoahongView Answer on Stackoverflow
Solution 12 - AndroidOrasView Answer on Stackoverflow
Solution 13 - AndroidJCDecaryView Answer on Stackoverflow
Solution 14 - AndroidAbdul GaffarView Answer on Stackoverflow
Solution 15 - AndroidBarrretttView Answer on Stackoverflow
Solution 16 - AndroidМаксим БагрянцевView Answer on Stackoverflow
Solution 17 - AndroidisaacView Answer on Stackoverflow
Solution 18 - AndroidVinod MauryaView Answer on Stackoverflow