How to set the image from drawable dynamically in

2020-01-27 10:15发布

I am storing my project related images in drawable folder. Also I am storing the image names in string variable and dynamically I am trying to set those images to the imageview. But the image is not displaying. Please help me in this regard.

My Code:

int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);

In the above code "imagename" is the string variable which contains the image name.

Thanks in advance

标签: android
14条回答
2楼-- · 2020-01-27 11:00
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);
查看更多
ゆ 、 Hurt°
3楼-- · 2020-01-27 11:00
imageView.setImageResource(R.drawable.picname);
查看更多
男人必须洒脱
4楼-- · 2020-01-27 11:01

This works fine for me.

final R.drawable drawableResources = new R.drawable(); 
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++) 
{
     resourceId[i] = fields[i].getInt(drawableResources);  
    /* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
   imageview.setImageResource(resourceId[any]);
}
查看更多
倾城 Initia
5楼-- · 2020-01-27 11:04

Try this:

String uri = "@drawable/myresource";  // where myresource (without the extension) is the file

int imageResource = getResources().getIdentifier(uri, null, getPackageName());

imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-27 11:05

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 
查看更多
▲ chillily
7楼-- · 2020-01-27 11:05
int[] phptr=new int[5];

adding image pointer to array

for(int lv=0;lv<3;lv++)
    {
        String id="a"+String.valueOf(lv+1);
        phptr[lv]= getResources().getIdentifier(id, "drawable", getPackageName());
    }

for(int loopvariable=0;loopvariable<3;loopvariable++) 
    {
        et[loopvariable] = findViewById(p[loopvariable]);
    }



for(int lv=0;lv<3;lv++)
    {
        et[k].setImageResource(phptr[k]);
    }
查看更多
登录 后发表回答