Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Change Button Font in Android?
Next article icon

How to Change Background Image by Button Clicking Event in Android?

Last Updated : 23 Feb, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Change Background Image by Button Clicking Event in Android Sample GIF

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.

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/relative_layout"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:gravity="center"     android:orientation="vertical"     tools:context=".MainActivity">      <!--Button to perform clicking event          to change background images-->     <Button         android:id="@+id/Button"         android:layout_width="150dp"         android:layout_height="52dp"         android:layout_margin="12dp"         android:background="#0F9D58"         android:text="Click Here"         android:textColor="#FFFFFF" />  </RelativeLayout> 

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.

Java
import android.os.Bundle; import android.view.View; import android.widget.Button;  import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat;  import java.util.Random;  public class MainActivity extends AppCompatActivity {     Button button;     View screenView;     int[] back_images;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // array creation of images which are stored         // in drawable folder under res folder         back_images = new int[]{R.drawable.geeksforgeeks, R.drawable.geeksforgeeks2,                                 R.drawable.geeksforgeeks3, R.drawable.geeksforgeeks4};         button = findViewById(R.id.Button);         screenView = findViewById(R.id.relative_layout);          button.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                  // fetching length of array                 int array_length = back_images.length;                  // object creation of random class                 Random random = new Random();                  // generation of random number                 int random_number = random.nextInt(array_length);                  // set background images on screenView                 // using setBackground() method.                 screenView.setBackground(ContextCompat.getDrawable(getApplicationContext(), back_images[random_number]));             }         });     } } 

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.

Output:

Github Link: For further help go through this repository. 


Next Article
How to Change Button Font in Android?

R

riyamathur
Improve
Article Tags :
  • Java
  • Android
  • Android-Misc
Practice Tags :
  • Java

Similar Reads

  • How to Change the Background Color After Clicking the Button in Android?
    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
    3 min read
  • How to Change the Background Color of Button in Android using ColorStateList?
    ColorStateList is an object which can define in an XML file that can be used to apply different colors on widgets (such as Buttons , etc) depending on the state of Widgets to which it is being applied . For Example, There are many states of Buttons like (pressed, focussed, or none of them ) and othe
    4 min read
  • How to Change Button Font in Android?
    A Button in Android is a UI element provided to a user to click to perform a certain action. A text can be set inside the button to name it. However, this text can be seen in a particular font only which is set by default. So in this article, we will show you how you could change the Button text fon
    2 min read
  • How to Change Background Color of ListView Items in Android?
    In Android, a ListView is a layout element that is used to display items in a list. This is the simplest form of displaying a list or array of items and one can choose from pre-developed layouts for displaying an element without creating a separate layout unlike in other similar views. Each item in
    2 min read
  • How to Set Gradient and Image Backgrounds for ActionBar in Android?
    UI plays quite significantly to keep the user engaged within the application. The very basic starts with developing a theme for an application. Themes may apply to all the UI elements within the application, but, the first thing that the user may notice is the Action Bar. Action Bar has a theme by d
    3 min read
  • How to Add Image on Floating Action Button in Android?
    A floating action button (FAB) is a user interface element in the mobile application that is typically circular and floats above the main content. It usually has a prominent color and icon, and it is used to provide quick access to the most commonly used action within the app. Step-by-Step Implement
    1 min read
  • How to Build a ChatGPT Like Image Generator Application in Android?
    Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application in which we will be able to ask any question and from that question, we will be able to
    5 min read
  • How to Create New ImageView Dynamically on Button Click in Android?
    In this article, we are going to implement a very important feature related to ImageView. Here we are going to add ImageView dynamically. We will be just changing the background color. Whenever we click on a button a new ImageView will be created. So here we are going to learn how to implement that
    3 min read
  • Handling Click Events in Button in Java Android
    Click Events are one of the basic operations often used in Java Android Development to create Java Android Applications. In this article, we will learn about how to Handle Click Events in Button in Android Java. Methods to Handle Click Events in a ButtonThere are 2 ways to handle the click event in
    4 min read
  • How to Change Colors of a Floating Action Button in Android?
    Android applications use the Floating Action Button for prompting the user to perform some important action within the android application. Floating Action Buttons in android applications are used to perform some important functionality within android applications. Many times in the android applicat
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences