Change Design on Button Press of Any Object in Android

First create an Android Project in the Eclipse IDE.

Android Project

Then open the XML file and drag and drop one button to the Graphical Layout of the XML file.

drag and drop one button in

Now create one XML file in the drawable folder and use two images for seeing the changes on a button press.

Create one xml file

drawable folder

Chosen qualifiers

Default Button Image.

Default Button Image

On Button Pressed Image.

Button Pressed Image

Paste both the images into the drawable folder.

design

Open the design.xml file and write the following code in the XML file:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2.    <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.          <item android:state_pressed="true"  
  4.                android:drawable="@drawable/buttonclicked" /> <!-- pressed -->  
  5.          <item android:drawable="@drawable/buttondefault" /> <!-- default -->  
  6.    </selector>  
Here buttonclicked and buttondefault are the image's name.

Now open the activity_main.xml file from the layout folder and here's the file code:
  1. <RelativeLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:paddingBottom="@dimen/activity_vertical_margin"  
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  8.     android:paddingRight="@dimen/activity_horizontal_margin"  
  9.     android:paddingTop="@dimen/activity_vertical_margin"  
  10.     tools:context="com.example.demo.MainActivity" >  
  11.     <Button  
  12.      android:id="@+id/button1"  
  13.      android:layout_width="wrap_content"  
  14.      android:layout_height="wrap_content"  
  15.      android:layout_alignParentLeft="true"  
  16.      android:layout_alignParentRight="true"  
  17.      android:layout_alignParentTop="true"  
  18.      android:layout_marginTop="97dp"  
  19.      android:text="Button"   
  20.      android:background="@drawable/design"/>  
  21. </RelativeLayout>  
android:background=”@drawable/design” is used to select the design.xml file in the background of the button.

Then run the Android application.

Before button is pressed

Before Button Pressed

On pressing the button

Button Pressed

So you can use this XML file is for any object in Android and is also useful for anything in design.xml such as images and colors.
Thank you.

Up Next
    Ebook Download
    View all
    Learn
    View all