Android – Button with background changed on click

One could think the behaviour in the bellow screen-shot is easy to accomplish but the truth is that it’s not. I’ve seen many questions and complicated solutions presented on stackoverflow with selectors and buttons and even people saying that it’s not possible to be done at all. Well, actually with regular buttons it is indeed difficult, but that’s why ImageButtons exist, so you may use this easier solution.

Button not pressed, than pressed

Use an ImageButton with background targeting a selector of two colors and the icon which doesn’t change as src image. The same way you could set a text.

    <ImageButton
        android:id="@+id/dialpad_Button"
        android:layout_width="54dp"
        android:layout_height="54dp"
        android:src="@drawable/btn_keypad"
        android:scaleType="centerInside"
        android:background="@drawable/btn_keypad_selector_button"
        android:layout_alignParentLeft="true"/>

The selector looks like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="false">
        <shape>
            <solid android:color="#552277AA" />
        </shape>
    </item>
	<item >
        <shape>
            <solid android:color="#ff2277AA" />
        </shape>
        </item>
</selector>

Leave a Reply

You must be logged in to post a comment.