在Android中基于字符串设置动态图像

San*_*ada -1 android android-imageview android-resources

考虑我在android的可绘制资源中有两个图像image_name1.png和image_name2.png。现在我要像下面这样设置图像

imageView.setImage(R.drawable.image_+"MyChoice"+.png);
Run Code Online (Sandbox Code Playgroud)

其中MyChoice可以是name1或name2或某些字符串

可能吗,或者我们有解决方案吗?

Nir*_*ara 5

你可以用uri做

String uri = "@drawable/imname"; //imname without extension

int imageResource = getResources().getIdentifier(uri, null, getPackageName()); //get image  resource

Drawable res = getResources().getDrawable(imageResource); // convert into drawble

imageView.setImageDrawable(res); // set as image
Run Code Online (Sandbox Code Playgroud)