Question

I have a few drawables:

R.drawable.pres01
R.drawable.pres02
R.drawable.pres03

I want to use SharedPreference to display the proper 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);

I converted the String to Integer, now how do I set the image source of ivPresident to the number based on the saved string.

So for example:

if someId is 01 the drawable for ivPresident is R.drawable.pres01

if someId is 02 the drawable for ivPresident is R.drawable.pres02

if someId is 03 the drawable for ivPresident is R.drawable.pres03

I tried the following but did not work:

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

How do I fix the code to achieve it?

Was it helpful?

Solution

What you want is:

Resources.getIdentifier(String name...)

See here

Build the string the way you are trying now.

EDIT:

String someId = prefs.getString("presNum", "");
int id = getResources().getIdentifier("pres0" + someId, "drawable", getPackageName())
ivPresident.setBackgroundResource(id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top