我有这个,工作正常:
public static Integer[] photos = new Integer[]
{R.drawable.photo1,R.drawable.photo2,R.drawable.photo3};
this.setImageResource(photos[mCellNumber]);
但是我决定将文件名放在XML文件中,而不是我做的,就像这样:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<array name="Red">
<item>R.drawable.photo1</item>
<item>R.drawable.photo2</item>
<item>R.drawable.photo3</item>
</array>
</resources>
尝试过这样的事情:
String[] month = getResources().getStringArray(R.array.Red);
this.setImageResource(month[mCellNumber]);
.. ..和
String[] month = getResources().getStringArray(R.array.Red);
int bla = Integer.parseInt(month[mCellNumber]);
this.setImageResource(bla);
我理解为什么它不起作用(strings / ints),但是我没有找到任何处理字符串到整数转换部分的简单方法,或者使用setImageResource和字符串作为参数。有什么建议吗?
答案 0 :(得分:1)
String[] month = getResources().getStringArray(R.array.Red);
int bla = Integer.parseInt(month[mCellNumber]);
看起来它会抛出异常R.drawable.photo1,因为字符串不是有效数字。
您只需保存名称,如photo1,photo2,photo3,然后执行以下操作:
...
Android - Store drawable ids in a custom XML file
你可以尝试只保存“joe_pic”这样的名字并获得this way
...
String uri = "drawable/icon";
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
}
但如果您已经添加了“R.drawable.joe_pic”,则可以使用String.split获取第3个字符串部分