0

I would like to change my Alert Dialog icon from a variable. Actualy I do :

AlertDialog.Builder alert = new AlertDialog.Builder( this); 
alert.setTitle("Level"+(OEDPrefs.level_number()));
alert.setIcon(R.drawable.icon);

but "icon" is always the same. I would like it to change according to the level number. I would like to do something like :

num = OEDPrefs.level_number();
icon_var = "icon"+num;

AlertDialog.Builder alert = new AlertDialog.Builder( this); 
alert.setTitle("Level"+(OEDPrefs.level_number()));
alert.setIcon(R.drawable.icon_var);

Is it possible? Thanks.

Pozinux
  • 964
  • 2
  • 10
  • 22
  • 2
    Does this answer your question? [How to access resource with dynamic name in my case?](https://stackoverflow.com/questions/6583843/how-to-access-resource-with-dynamic-name-in-my-case) – jo3rn Mar 30 '20 at 13:37

2 Answers2

0

Use an array of icons for different levels. Turning to a specific element of the array you will receive the id of the icon for a certain level

int[] icons = {R.drawable.icon1,R.drawable.icon2 ... };

get an icon for i level

int icon = icons[i];
Destroyer
  • 785
  • 8
  • 20
0

Something like this should work:

num = OEDPrefs.level_number();
icon_var = "icon"+num;

int id = getResources().getIdentifier(icon_var , "drawable", context.getPackageName());

AlertDialog.Builder alert = new AlertDialog.Builder( this); 
alert.setTitle("Level"+(OEDPrefs.level_number()));
alert.setIcon(id);
apmartin1991
  • 3,064
  • 1
  • 23
  • 44