Monday, August 24, 2015

How to set ImageButton pressed state background in Android

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F4F0EC"
    android:padding="16dp"
    tools:context=".MainActivity">

    <!-- ImageButton with default click effect/pressed state -->
    <ImageButton
        android:id="@+id/ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:src="@drawable/share_transparent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--
        ImageButton with custom pressed state.
        ImageButton selector.
        ImageButton click effect.
        A transparent png image used for ImageButton.
    -->
    <ImageButton
        android:id="@+id/ib2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:src="@drawable/share_transparent"
        android:background="@drawable/image_button_selector"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ib" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/drawable/image_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!--image button pressed state background color-->
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#C0BB91" />
            <corners android:radius="5dp"/>
        </shape>
    </item>

    <!--image button focused state background color-->
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="#E4E6D5" />
            <corners android:radius="5dp"/>
        </shape>
    </item>

    <!--image button default background color-->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#E4E6D5" />
            <corners android:radius="5dp"/>
        </shape>
    </item>
</selector>