Using setImageDrawable dynamically to set image in an ImageView

前端 未结 17 1719
借酒劲吻你
借酒劲吻你 2020-12-04 08:22

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

相关标签:
17条回答
  • 2020-12-04 08:49

    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);
    
    0 讨论(0)
  • 2020-12-04 08:50

    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);
    
    0 讨论(0)
  • 2020-12-04 08:50

    You can try to use this code:

    ImageView ImgView = (ImageView)findViewById(R.id.ImgView);
    ImgView.setImageResource(R.drawable.myicon);
    
    0 讨论(0)
  • 2020-12-04 08:51
    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));
    
    0 讨论(0)
  • 2020-12-04 08:53

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

    0 讨论(0)
  • 2020-12-04 08:54

    As simple as this answer:

    Drawable myDrawable = getResources().getDrawable(R.drawable.pic);
    imageview.setImageDrawable(myDrawable);
    
    0 讨论(0)
提交回复
热议问题