How to set Button pressed state background color in Android

Button background color drawable state
Button control is commonly used to tap on it to perform some tasks within an Android application. The Button shows a default background color when users press it.Android developers can easily change the default background color of the button’s pressed state. In this android app development tutorial, we will see how can we change the button’s pressed state background color.

First of all, we will write the background property on the Button widget XML file. The Button’s background property value points to an XML drawable file which includes a selector with the button’s different states colors and shapes values. Such as, Button’s default state, focused state, and pressed state’s background color.

Within the selector pressed state’s item we will put a background color that we want to replace with the button’s default pressed state background color. Here we can also specify the button’s shape and corner radius.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8FF">

    <Button
        android:id="@+id/push_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_bg_color_with_state"
        android:padding="15dp"
        android:text="Button Drawable State"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
code>
res/drawable/button_bg_color_with_state.xml

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

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

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