使用SharedPreference定义可绘制资源

时间:2013-09-16 17:48:34

标签: java android android-background

我有一些抽奖:

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的图像源设置为数字。

例如:

如果someId01 ivPresident的可绘制内容为R.drawable.pres01

如果someId02 ivPresident的可绘制内容为R.drawable.pres02

如果someId03 ivPresident的可绘制内容为R.drawable.pres03

我尝试了以下但没有奏效:

ivPresident.setBackground(R.drawable.pres + inAdd);

如何修复代码来实现它?

1 个答案:

答案 0 :(得分:1)

你想要的是:

Resources.getIdentifier(String name...)

请参阅here

按照您现在尝试的方式构建字符串。

编辑:

String someId = prefs.getString("presNum", "");
int id = getResources().getIdentifier("pres0" + someId, "drawable", getPackageName())
ivPresident.setBackgroundResource(id);