Android tutorial: custom button background (created programatically)

29 06 2013

This post is an extension to the Android custom button layout tutorial.

Creating custom button background is described here. There, in point 3, I show how to build an XML file with selector background.

The selector file has definitions of backgrounds that are shown depending on a button state: if button is pressed, then show pressed background, else show normal background

XML definition is suitable when you know at a compile time which images you will use. When you have to decide at runtime (for example build layout dynamically) – it is not enough. Then you can substitute the XML file with programatically created object: StateListDrawable.

It means that this XML:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="" >
    <item android:state_pressed="true" android:drawable="@drawable/button_left_pressed"/>
    <item android:state_focused="true" android:drawable="@drawable/button_left_pressed"/>
    <item android:drawable="@drawable/button_left_normal"/>

is exactly the same, interchangeable and can be created in Java code this way:

int buttonPressedResId = R.drawable.button_left_pressed;
int buttonNormalResId = R.drawable.button_left_normal;

Resources resources = getApplicationContext().getResources();

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, resources.getDrawable(buttonPressedResId));
states.addState(new int[] {android.R.attr.state_focused}, resources.getDrawable(buttonPressedResId));
states.addState(new int[] { }, resources.getDrawable(buttonNormalResId));
((Button) findViewById(;

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



2 responses

29 06 2013
Android custom button layout tutorial | Looks OK!

[…] There are two ways of creating such background. The common one is to define it in XML file – this way I will describe here. The other, more elastic way is to define it at runtime in Java Code. And this is described in another tutorial. […]

23 06 2016

I used to be recommended this website by means of my
cousin. I’m now not sure whether or not this submit is
written by way of him as nobody else know such designated about my trouble.
You’re amazing! Thank you!

Give Your feedback:

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

You are commenting using your 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

%d bloggers like this: