androidandroid-layoutandroid-drawablerippledrawable

Add ripple effect to my button with button background color?


I created a button and I want to add ripple effect to that button!

I created a button bg XML file: (bg_btn.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient android:startColor="#FFFFFF" android:endColor="#00FF00" android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>

And this is my ripple effect file: (ripple_bg.xml)

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#f816a463"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
        </shape>
    </item>
</ripple>

And This is my Button which I want to add ripple effect:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="173dp"
android:textColor="#fff"
android:background="@drawable/ripple_bg"
android:clickable="true" />

But after adding ripple effect button background is transparent, and button display only when clicked, like this:

Before Click

On Click

But I need both button background color and ripple effect, I found some of this code in different blogs of Stack Overflow, but still it is not working!


Solution

  • Here is another drawable xml for those who want to add all together gradient background, corner radius and ripple effect:

    <?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/colorPrimaryDark">
        <item android:id="@android:id/mask">
            <shape android:shape="rectangle">
                <solid android:color="@color/colorPrimaryDark" />
                <corners android:radius="@dimen/button_radius_large" />
            </shape>
        </item>
    
        <item android:id="@android:id/background">
            <shape android:shape="rectangle">
                <gradient
                    android:angle="90"
                    android:endColor="@color/colorPrimaryLight"
                    android:startColor="@color/colorPrimary"
                    android:type="linear" />
                <corners android:radius="@dimen/button_radius_large" />
            </shape>
        </item>
    </ripple>
    

    Add this to the background of your button.

    <Button
        ...
        android:background="@drawable/button_background" />
    

    PS: this answer works for android api 21 and above.