我有一些抽奖:
R.drawable.pres01
R.drawable.pres02
R.drawable.pres03
我想使用SharedPreference
来显示正确的drawable:
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
String someId;
ImageView ivPresident;
int inAdd;
prefs = this.getSharedPreferences("pNum", Context.MODE_PRIVATE);
someId = prefs.getString("presNum", "");
inAdd = Integer.parseInt(someId);
ivPresident = (ImageView) findViewById(R.id.imgViewPresident);
我将String转换为Integer,现在如何根据保存的字符串将ivPresident
的图像源设置为数字。
例如:
如果someId
为01
ivPresident
的可绘制内容为R.drawable.pres01
如果someId
为02
ivPresident
的可绘制内容为R.drawable.pres02
如果someId
为03
ivPresident
的可绘制内容为R.drawable.pres03
我尝试了以下但没有奏效:
ivPresident.setBackground(R.drawable.pres + inAdd);
如何修复代码来实现它?
答案 0 :(得分:1)
你想要的是:
Resources.getIdentifier(String name...)
请参阅here
按照您现在尝试的方式构建字符串。
编辑:
String someId = prefs.getString("presNum", "");
int id = getResources().getIdentifier("pres0" + someId, "drawable", getPackageName())
ivPresident.setBackgroundResource(id);