Generate a Random Color on Button Click — Android Studio
Sometimes we need to generate random colors every time in our project.it is very easy but tricky.
we know there are lots of types of color codes. one of them RGB where the value of each color (Red, Green, Blue ) should be 0–255.
we generate a number between 0 to 255 for each color (RGB) by using the Random() function and create a color object using these numbers which are different every time.
Step by Step Implementation :
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code.
activity_main.xml
<?xml version=”1.0" encoding=”utf-8"?><android.support.constraint.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:id=”@+id/layout” android:layout_width=”match_parent” android:layout_height=”match_parent” tools:context=”.MainActivity”>
<Button android:id=”@+id/button” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”generate random color” app:layout_constraintBottom_toBottomOf=”parent” app:layout_constraintLeft_toLeftOf=”parent” app:layout_constraintRight_toRightOf=”parent” app:layout_constraintTop_toTopOf=”parent” />
</android.support.constraint.ConstraintLayout>
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code.
MainActivity.java
package com.hemant.patel;
import android.graphics.Color;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
layout.setBackgroundColor(color);
}
});
}
}
I hope you like this implementation. please share this with your friends and don’t forget to follow me for useful content.
Hemant Patel
Android App Developer | UI Designer | Competitive Programmer
Github | Linkedin | Medium | StackOverflow | GeeksforGeeks