Wednesday, January 21, 2015

java - How to generate a random number

activity_main.xml code snippet

<TextView
 android:id="@+id/text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Random Number"
 android:textSize="75sp"
 android:textColor="#ff0000"
 >
</TextView>
<Button
 android:id="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Generate Random Number"
 android:onClick="perform_action"
 android:textSize="20sp"
 >
</Button>
MainActivity.java code snippet

public void perform_action(View v)
{
 /*
  the following example code demonstrate us how can we
   generate a random number programmaitically in java code
  */

 //define a new Random class
 Random r = new Random();

 //get the next random number
 /*
  nextInt(int n) method return a random number
  between 0 and provided integer value.

  including zero and excluding provided integer value.

  random number will be bellow than
  provided integer

  if we set the argument inetger to 3 then system will
  generate a random number from 0,1 or 2
  */
 int randomNumber = r.nextInt(5);

 //reference the textview widget
 TextView tv = (TextView) findViewById(R.id.text_view);

 //display the random number to textview
 tv.setText(String.valueOf(randomNumber));
}
Imported Class

import android.view.View;
import android.widget.TextView;
import java.util.Random;
More android examples