Ollie Smith
Ollie Smith

Reputation: 23

Set button text with the random result

I'm doing a math quiz and I need to know how to set the button text with a random result from a random calculation?

public class Mat extends AppCompatActivity {

Random x = new Random();
int ran1 = x.nextInt(50);
int ran2 = x.nextInt(50) +1;
int rSoma = ran1 + ran2;
int rSub = ran1 - ran2;
Button bAlternativa1;
Button bAlternativa2;
Button bAlternativa3;
Button bAlternativa4;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mat);
    bAlternativa1 = (Button)findViewById(R.id.a1);
    bAlternativa2 = (Button)findViewById(R.id.a2);
    bAlternativa3 = (Button)findViewById(R.id.a3);
    bAlternativa4 = (Button)findViewById(R.id.a4);


    }


}

I need to set the text of one of that bAlternativa's buttons to the result of the rSoma and rSub.

I'm sorry I didn't explain it very well

Look at this image:enter image description here

The ImageView of the bear will the calculation. The result from the random calculation has to switch between the buttons. One of them will have the right answer and the others will have a random result.

Upvotes: 2

Views: 83

Answers (2)

anomeric
anomeric

Reputation: 698

You can place this snippet inside of onCreate or any other method after the buttons have been initialized.

bAlternativa1.setText(Integer.toString(rSoma));

or

bAlternativa2.setText(Integer.toString(rSub));

If you want to set this text immediately then replace your onCreate method with this one:

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mat);
    bAlternativa1 = (Button)findViewById(R.id.a1);
    bAlternativa2 = (Button)findViewbyId(R.id.a2);
    // initialize other buttons
    bAlternativ1.setText(Integer.toString(rSoma));
    bAlternativ2.setText(Integer.toString(rSub));
    // you can interchange bAlternativa1/bAlternativa2 with any of your other buttons
    // you can put any int inside of Integer.toString(int);
}

Upvotes: 0

Eselfar
Eselfar

Reputation: 3869

Just call setText on the button you want the result to be displayed, with the result:

bAlternativa.setText(randomResult)

EDIT

As you want to display an int you need first to convert it to a string. You can do something like that:

int randomResult = ... // your random result
String result = Integer.toString(randomResult);

Then you can set your result to the Button.

Upvotes: 1

Related Questions