Custom Button Backgrounds Using A Selector XML Layout

Custom Button Backgrounds Using A Selector XML Layout

Explains how to create a selector for a drawable XML file. One of the main uses of this is for easy rollover buttons but there are many uses beyond that. This is a great tutorial for a little documented feature.

First of all, we need to have (at least) one button in the content view of our activity. What is going to be special about this button is, that we are going to define a background drawable. As result this is the main.xml:

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

As you can see, I only added 1 line to the minimal Button declaration. Now we need to definemy_button.

The Selector xml tag we were talking about is a drawable xml resource. This means we need to make an xml file in the drawable folder with the name we want. For this tutorial we named it ‘my_button.xml’. In my_button we define 4 states (as a button has 4 states: not pressed and not focused, pressed and focused, pressed and not focused, not pressed and focused) with each of those states having their own drawable.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/focused" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/focusedpressed" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pressed" />
    <item android:drawable="@drawable/defaultbutton" />
</selector>

These png drawables will be in the attachment. So what did we just do? For each one of the 4 states defined earlier, we define a drawable. For the first <item> tag this means the button will use the focused drawable (called focused.png) when the button is focused, but _not_ pressed. This you can see in the attributes: state_focused and state_pressed. The second <item> defines that the button will use the focusedpressed drawable when the Button is focused and pressed. The third <item> defines that the button will use the pressed drawable when … (this one is as an exercise for you). And the last <item> defines the default drawable.

Now, start running this example and you will have your own custom button.

from: http://androidwizard.net/2010/02/custom-button-backgrounds-using-a-selector-xml-layout/

你可能感兴趣的:(.net,xml,android)