根据字符串在 android 中设置动态图像
Setting dynamic image in android based on a string
假设我在 android 的可绘制资源中有两个图像 image_name1.png、image_name2.png。现在我想像下面这样设置图像,
imageView.setImage(R.drawable.image_+"MyChoice"+.png);
其中 MyChoice 可以是 name1 或 name2 或一些字符串
这可能吗,或者我们有什么解决方案可以实现吗?
你不能那样做。你可以做的是:
int images[] = {R.drawable.image1, R.drawable.image2};
imageView.setImage(images[mychoice]);
如果你想做字符串而不是整数索引,或者与散列类似的东西 table。
顺便说一句,您不要将 .png 放在代码中的可绘制对象名称中。 drawable 的要点是你不需要知道它是 png、jpg 还是 xml.
你可以通过 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
有两种可能
1.
int MyChoice=1 or 2;
`imageView.setImage(R.drawable.image_+MyChoice+.png);`
第二个是
int image=Integer.parseInt("R.drawable.image_"+MyChoice+".png");
imageView.setImage(image);
Resources.getIdentifier
满足您的需求。
int resId = context.getResources().getIdentifier("image_"+myChoice, "drawable", "com.myapp.mypackage");
if(resId == 0) {
resId = R.drawable.default;
}
imageView.setImageResource(resId);
假设我在 android 的可绘制资源中有两个图像 image_name1.png、image_name2.png。现在我想像下面这样设置图像,
imageView.setImage(R.drawable.image_+"MyChoice"+.png);
其中 MyChoice 可以是 name1 或 name2 或一些字符串
这可能吗,或者我们有什么解决方案可以实现吗?
你不能那样做。你可以做的是:
int images[] = {R.drawable.image1, R.drawable.image2};
imageView.setImage(images[mychoice]);
如果你想做字符串而不是整数索引,或者与散列类似的东西 table。
顺便说一句,您不要将 .png 放在代码中的可绘制对象名称中。 drawable 的要点是你不需要知道它是 png、jpg 还是 xml.
你可以通过 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
有两种可能
1.
int MyChoice=1 or 2;
`imageView.setImage(R.drawable.image_+MyChoice+.png);`
第二个是
int image=Integer.parseInt("R.drawable.image_"+MyChoice+".png");
imageView.setImage(image);
Resources.getIdentifier
满足您的需求。
int resId = context.getResources().getIdentifier("image_"+myChoice, "drawable", "com.myapp.mypackage");
if(resId == 0) {
resId = R.drawable.default;
}
imageView.setImageResource(resId);