3

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
9
  • What, in words, is it you want to happen? Do you want to set the text on one of your buttons? Commented Jul 20, 2014 at 21:50
  • Y, the num will have 1 or 2, so the total string will be "button1" or "button2". Commented Jul 20, 2014 at 21:51
  • I just dont know why i have "-1" if i have a question to ask. Please help me. I realy need know how to do this. Commented Jul 20, 2014 at 21:53
  • total.setTest(some_text); You want to change the text of a string? Commented Jul 20, 2014 at 21:53
  • No, i want change the text of the button. The total.setTest(some_text); is just a idia. Commented Jul 20, 2014 at 21:54

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I just dont vote up becouse dont have 15 reputation ^^
That's cool. If you gain some rep and remember, come on back :)
You can ease the code by using Button[] buttons = { button1, button2 };
By the way, for future posts, it is better to edit your answer than deleting the answer and posting a new one.
Why exactly is that better? I deleted the first one as to remove the erroneous comments. I will do whatever is better in the future, but I really did think I had done the better option.
|
0

No, i want change the text of the button.

Then just do something like this

button1.setText("Just some strings here");

3 Comments

The problem is that OP wants the button that is getting its text changed to be random.
I want change the text of a random button. But problem solve thanks anyway.
Y, sorry my englisj is low.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.