This tutorial is the simplest example of changing the background color with a touch.
First start with the xml file i.e activity_main.xml
In actual you don't really have to do anything in the xml file but just for understanding, just type this line in the base / Constraint Layout
android:background="@color/white"So that the complete xml script becomes:
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
It already has the id defined so no worries.
Now let's move on to the Java code i.e MainActivity.java file:
Here create an object of Constraint Layout
ConstraintLayout cl;and initialize it in the onCreate method
cl = findViewById(R.id.main);finally in the onUserInteraction method, just set the color you want
cl.setBackgroundColor(Color.WHITE);If you want random colors on every interaction, just create an array of colors in this way with a random object:
int[] color = {Color.BLUE, Color.CYAN, Color.MAGENTA,
Color.BLACK, Color.GRAY, Color.GREEN, Color.RED};
Random random = new Random();In onUserInteraction use the random object to set a random color:
cl.setBackgroundColor(color[random.nextInt(color.length-1)]);So now the complete Java code becomes:
package com.example.backgroundcolorchanger;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ConstraintLayout cl;
int[] color = {Color.BLUE, Color.CYAN, Color.MAGENTA,
Color.BLACK, Color.GRAY, Color.GREEN, Color.RED};
Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cl = findViewById(R.id.main);
}
@Override
public void onUserInteraction() {
super.onUserInteraction();
cl.setBackgroundColor(color[random.nextInt(color.length-1)]);
}
}



No comments:
Post a Comment