Using a State List Drawable as a button background image

Hi there!

As a response to a subscriber’s question, I decided to present an example of making use of the State List Drawable as a Button’s background image.

For using text and image on a Button widget, you can make use of the appropriate attributes, as in the following example:

<Button
        android:layout_height="wrap_content"
    	android:layout_width="wrap_content"
        android:background="@drawable/button_background"
        android:text="@string/button_text"/>

For the background drawable you can use either an image or a State List Drawable, which is actually an XML file defining the images that the button should use in each of its statuses. Here is an example:
– res/drawable/button_status_list_drawable.xml (the status list drawable, which will later be used as a drawable itself)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pressed_img" android:state_pressed="true"/>
    <item android:drawable="@drawable/hovered_img" android:state_hovered="true"/>
    <item android:drawable="@drawable/default_img"/>    
</selector>

– main.xml (an example of how to refer to the state list drawable)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >    
    <Button
        android:layout_height="wrap_content"
    	android:layout_width="wrap_content"
        android:background="@drawable/state_list_drawable"
        android:text="@string/button_text"/>
</LinearLayout>

Hope this post will help you with what you are trying to do! In any case, I would suggest you to have a look at the Android SDK documentation of the Button widget:
http://developer.android.com/reference/android/widget/Button.html

In case you need further help, don’t hesitate to contact me!

Advertisements

About sermojohn

Professional Software Engineer
This entry was posted in Android and tagged , , , , , , . Bookmark the permalink.

One Response to Using a State List Drawable as a button background image

  1. Pingback: Android: how to use view states with nested drawable resources? : Android Community - For Application Development

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s