Android tutorial: custom button background (created programatically)

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="http://schemas.android.com/apk/res/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"/>
</selector>

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(R.id.calc_addPerson_button)).setBackgroundDrawable(states);

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 thoughts on “Android tutorial: custom button background (created programatically)

  1. 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!

Leave a reply to Android custom button layout tutorial | Looks OK! Cancel reply