reza reza - 5 months ago 12
Android Question

Change ImageButton backgound color on press

I have seen many examples for ImageButton on hover, but they change the image. I just want to change the background color.

This is my selector -

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:color="#4B88F7"/>
<item android:state_pressed="false" android:color="#121212"/>


And my ImageButton -

<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="@color/actionbar_btn"
android:src="@drawable/ic_remove" />

Answer

Create a file custom_selector.xml in res/drawable/ directory with the following content:

<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/btn_pressed"/>
    <item android:state_pressed="false" android:drawable="@color/btn_released"/>
</selector>

Then to apply this background to ImageButton by setting it as the background:

<ImageButton
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="2"
    android:background="@drawable/custom_selector.xml"
    android:src="@drawable/ic_remove" />

See https://developer.android.com/guide/topics/resources/color-list-resource.html