![]() |
VOOZH | about |
In this article, we will see how we can change the background of the screen by clicking a button. For this, we will be using the onClick() method. When we click on the button the onClick function is called. To set the click handler event for the button we need to define the android:onClick attribute in the XML file. We can also use onClickListener() in the Java file to call this function programmatically when the button is clicked. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
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: Define Colors
It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors.
Add the below lines inside the colors.xml file.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
Step 4: Working with the MainActivity.java file
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Output: