How to Change Background Image by Button Clicking Event in Android?
Background Images play an important role in the beautification of any application. Hence, most social media applications like WhatsApp, Messenger provides this as a part of their feature to their users. So, keeping this in mind we will be going to develop an android application in which background images will get change by button clicking.
What we are going to build in this article?
We will be building a simple application in which we will be displaying a Button and by using clicking the event of the button we will change the background images in the application. Note that will we make an array of images that were saved in a drawable folder and we will access those images randomly using Random class. We are going to implement this project using the Java language. So, without wasting further time let’s go to the implementation. 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 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: Collect Images and Save them
Now, download some images for background and then navigate to app > res > drawable folder and save all downloaded images in a drawable folder by using the copy-paste method.
Step 3: Working with the activity_main.xml file
Now, we will design the layout part of our application.So, navigate to the app> res > layout > activity_main.xml ,and paste below written code in activity_main.xml file.
Step 4: Working with the MainActivity.java file
Next, we will develop the backend part of the application. So, navigate to the app > java >package name> MainActivity.java and paste the below-written code in the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Now our application is ready to install. So, click on the run button to run the application. Here is the output video of the application.
Github Link: For further help go through this repository.