Wednesday 27 April 2016

android - How to call code to generate a random number?

What I'm currently using is the below code, but this is generating a random number once at the start (defined as d20), then just calling that number whenever I click the button. How can I change this to generate that code (rndNumbers.nextInt(20) +1) on the click of a button.




I realize that other people have asked similar questions, but I've not seen it be exactly the same as mine (and I'm almost a total beginner, so I didn't understand the other people's code too well).






import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Random rndNumbers = new Random();
int d20 = rndNumbers.nextInt(20) +1;
Button roll;
TextView display;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
roll = (Button) findViewById(R.id.bRoll);
display = (TextView) findViewById(R.id.tvDisplay);
roll.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {
// TODO Auto-generated method stub
display.setText("The dice lands on " + d20);
}
});

};




@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...