Emanuel Graf Emanuel Graf - 5 months ago 19
Java Question

Get Drawable id for dynamically generated Resource Name/String

the .setBackgroundResource can only accept an int and not a string, but it would look much nicer if it wouldnt be so fat and ugly for every 'levelup' for fabrik, so is there a way to simplify this:

datafab1 = getSharedPreferences("datafab1", MODE_PRIVATE);

if (datafab1.getInt("Level", 1) == 3) {
Fabrik1.setBackgroundResource(R.drawable.fablvl3);
}
if (datafab1.getInt("Level", 1) == 4) {
Fabrik1.setBackgroundResource(R.drawable.fablvl4);
}
if (datafab1.getInt("Level", 1) == 5) {
Fabrik1.setBackgroundResource(R.drawable.fablvl5);
}
if (datafab1.getInt("Level", 1) == 6) {
Fabrik1.setBackgroundResource(R.drawable.fablvl6);
}
if (datafab1.getInt("Level", 1) == 7) {
Fabrik1.setBackgroundResource(R.drawable.fablvl7);
}
if (datafab1.getInt("Level", 1) == 8) {
Fabrik1.setBackgroundResource(R.drawable.fablvl8);
}
if (datafab1.getInt("Level", 1) == 9) {
Fabrik1.setBackgroundResource(R.drawable.fablvl9);
}
if (datafab1.getInt("Level", 1) == 10) {
Fabrik1.setBackgroundResource(R.drawable.fablvl10);
}


to something like this:

datafab1 = getSharedPreferences("datafab1", MODE_PRIVATE);

String fablvl1nr = "R.drawable.fablvl"+Integer.toString(datafab1.getInt("Level", 1));
Fabrik1.setBackgroundResource(fablvl1nr);

Answer

The method you are looking for is getIdentifier of the Resource class:

int i = datafab1.getInt("Level", 1);
int id= getResources().getIdentifier("fablvl"+i, "drawable", getPackageName());