Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java "Convert" String to Button

Tags:

java

android

I have this code:

Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);

String object = "button";
int num;
num = r.nextInt(3 - 1) + 1;
String total = object + num;

I want do set the text for one of the buttons chosen randomly. Something like this:

button<num>.setText(some_text);
      ^ here instead of <num> should be 1 or 2
        and has to be chosen randomly

1 Answers

Like Ondkloss said, you can add your buttons to an array, then randomly select one from that array.

Button[] buttonArray = new Button[2];
buttonArray[0] = button1;
buttonArray[1] = button2;

Random r = new Random();

buttonArray[r.nextInt(2)].setText(someRandomText);

Keep in mind that if you change the number of buttons you will need to change the numbers that I have used (new Button[2] & r.nextInt(2)). My solution works specifically for an array of length 2 containing only 2 buttons. But other than changing the numbers in the array creation and the random number generation to match the number of buttons you have, this solution should work just fine.

like image 125
takendarkk Avatar answered May 22 '26 10:05

takendarkk