I am trying to write a loop to set the resources of 5 dice. If I change the “imgBtnName in the last line of the code to any of the dice names (such as “dice1”), the line doesn’t error. However, when I try to concatenate the name to fit the for loop, the following error notification on the setImageesource:
error
The method setImageResource(int) is undefined for the type String
Any ideas? I feel like I may be missing a syntax similar to the “int id” line.
code
public void PlayGame()
{
dice1 = (ImageButton)findViewById(R.id.btndice1);
dice2 = (ImageButton)findViewById(R.id.btndice2);
dice3 = (ImageButton)findViewById(R.id.btndice3);
dice4 = (ImageButton)findViewById(R.id.btndice4);
dice5 = (ImageButton)findViewById(R.id.btndice5);
begin = (Button)findViewById(R.id.btnroll);
roll = (Button)findViewById(R.id.btnbegin);
begin.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Random rand = new Random();
for (int i = 0; i < 6; i = i + 1) {
int rndInt = rand.nextInt(6) + 1; // Random number between 1 and 6
String imgBtnName = "dice" + (i + 1);
String imgName = "die" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgBtnName.setImageResource(id); //trying use the imgButnName string to set dice1, dice2, dice3 etc to set the imagebutton resource
}
}
});
}
Wrap your ImageViews in an arry and loop around them