How to Generate the ID of a Random Toggle Button, Then SetChecked(True) That Specific Toggle Button

493 views Asked by At

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
2

There are 2 answers

3
Vivek Khare On BEST ANSWER

Use this line instead

((ToggleButton)findViewById(buttonId)).setChecked(true);
3
Gabe Sechan On

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.