Android Studio Tutorial : Random Number Generator

This is a tutorial on how to build a simple random number generator in Android Studio. The app will generate a random number from 0 to 999

Layout xml

Here the layout for the app is created.

The layout consist of two main features, a button for the user to click to generate a number and a text view for the output to be displayed when user clicks the button.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/generate"
        android:layout_width="248dp"
        android:layout_height="84dp"
        android:text="Generate random number"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/generatedNumber"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:maxLines="1"
        android:textSize="45sp"
        android:textStyle="bold"
        app:autoSizeTextType="uniform"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Java Class

The java class is created here.

package com.example.randomnumbergenerator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Random numRandom = new Random();

        Button buttonGenerate = (Button)findViewById(R.id.generate);
        final TextView Output_Generated_Number 

(TextView)findViewById(R.id.generatedNumber);

        buttonGenerate.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
    Output_Generated_Number.setText(String.valueOf(numRandom.nextInt(1000)));
            }
        });
    }
}

That’s it! The app should be ready to run.

Run the app and click the button to generate your random number.

Check out more tutorials below!