1

I have two ToggleButtons and I want to be able to randomly select the id of one of those buttons, and set check that button to true. I tried This but is does not work as setChecked is not available for an Int or String. Any help would be much Appreciated.

int[] buttonIds = new int[] {R.id.player1Button, R.id.player2Button};
Random rand = new Random();
int num = rand.nextInt(buttonIds.length);
int buttonId = buttonIds[num];
findViewById(buttonId).toString();
String randomButton = getString(buttonId);
randomButton.setChecked(true); /// THIS LINE OF CODE WILL NOT WORK
kh_eden147
  • 43
  • 2
  • 9

2 Answers2

2

Use this line instead

((ToggleButton)findViewById(buttonId)).setChecked(true);
GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
Vivek Khare
  • 162
  • 4
0

You're getting a little confused at the end. Your code to pick a random id is fine. But a ToggleButton is a class. It is not a String. If you convert it into a String via toString(), it will not have any of the toggleButton functions. Instead you want to findViewById to get the id, cast it to a ToggleButton and call setChecked on that ToggleButton.

GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thank you friend I have managed to get it to work by doing like you said. I changed the last three line to this : `findViewById(buttonId);` `ToggleButton randomButton = (ToggleButton) findViewById(buttonId);` `randomButton.setChecked(true);` – kh_eden147 Jun 24 '15 at 23:03
  • However as one of the ToggleButtons are already checked on startup, sometimes both togglebuttons can end up being checked. Is there a way of getting the id of the the remaining button in the array so i can setCheck it to false at the same time – kh_eden147 Jun 24 '15 at 23:11
  • There's only 2 ids- the random index you pick is either 0 or 1. The other of those 2 values is the other button's index. – Gabe Sechan Jun 24 '15 at 23:59