Android Dev: Custom button with no PNG’s

{lang: 'en-GB'}


There is no denying that PNG’s (and .9.png’s) are the way to go if you are graphically talented.

I am not! I prefer using xml to define drawable shapes / gradient / and strokes. For a while I have been merely replacing the background of my buttons with an xml shape. It works, but there is no sense that something has been pressed, and no focus highlight.

Here is an example of how to properly skin your buttons (using XML). I created 3 xml files to define normal, pressed, and focused. Then another XML to link them together into a selector:

button_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:endColor="#CCCCCC"
        android:angle="-90" />
    <stroke
    	android:width="1dp"
    	android:color="#999999"/>
</shape>

button_pressed.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#CCCCCC"
        android:endColor="#FFFFFF"
        android:angle="-90" />
    <stroke
    	android:width="1dp"
    	android:color="#999999"/>
</shape>

button_focus.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:endColor="#FFFFFF"
        android:angle="-90" />
    <stroke
    	android:width="1dp"
    	android:color="#999999"/>
</shape>

And here is the selector (mybutton_background.xml):

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_focused="true"
        android:drawable="@drawable/button_focus" >
    </item>

    <item
        android:state_pressed="true"
        android:drawable="@drawable/button_pressed" >
	</item>

    <item
        android:drawable="@drawable/button_normal" >
    </item>
</selector>

To apply the skin, simply select “mybutton_background” as your background resource on your button.


Google+ Comments

Comments are closed.