Reputation: 29
Thats An easy questions for those who been in the android coding scene for long enought ! I have done researches , Studies about this questions. Tried it , But always had errors when Ran the application.
The questions is , How could I make a button , Show a Random number between 1 and 100 on a textview ?
Upvotes: 1
Views: 9100
Reputation: 2698
final Random r = new Random();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.onClickListener(){
public void onClick(...){
textView.setText(Integer.toString(r.nextInt(100)+1));
}
});
Upvotes: 8
Reputation: 83311
Here's some sample code that might help.
public class SampleActivity extends Activity {
private TextView displayRandInt;
private Button updateRandInt;
private static final Random rand = new Random();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(/* Your Activity's XML layout id */);
/* Setup your Activity */
// Find the views (their ids should be specified in the XML layout file)
displayRandInt = (TextView) findViewById(R.id.displayRandInt);
updateRandInt = (Button) findViewById(R.id.updateRandInt);
// Give the Button an onClickListener
updateRandInt.setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
int randInt = rand.nextInt(100)+1;
displayRandInt.setText(String.valueOf(randInt));
}
});
}
}
Upvotes: 2