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:09

This works for me (dont use the extension of the image, just the name):

String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
查看更多
干净又极端
3楼-- · 2020-01-27 11:12

getDrawable() is deprecated, so try this

imageView.setImageResource(R.drawable.fileName)
查看更多
登录 后发表回答