Skip to main content

Material ripple effect on Android Buttons

If you observe the buttons in recent apps, they all have ripple effect when you touch the buttons. How do you achieve it in your own app?

Solution 1: 

Change the foreground of the button to selectableItemBackground as shown below.


<button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:foreground="?android:atrr/selectableItemBackground"
       android:background="@color/buttonColor"
 />

Works for : API 23 and above

Solution 2:

 Set the value for backgroundTint instead of changing the background.

Works for : API 21 and above

<button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content”
      android:backgroundTint="@color/buttonColor"
 />
This gives ripple effect with the color specified.

Solution 3:


You can specify the ripple effect using xml and use this xml file as background for the button. But again ripple tag is available only on Sdk 21 and above. If your minimum sdk is lower than 21, then you need to create this drawable in the folder drawable-v21.

/res/drawable-v21/ripplebg.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple android:color="@color/green"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/blue"/>

</ripple>


This will show ripple in green color in a background of blue color.






ripple tag is used to specify the ripple colors.

You can omit the item tag, in which case, ripple will be shown on parent's background.

You specify this as a background for button as shown below.

 <Button
     android:id="@+id/button_id"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Next"
     android:background="@drawable/ripplebg"
 />

    
But the problem is, what happens for Sdks less than 21? How do you write for ripplebg.xml in drawable folder?

For that, you can have a normal button with a background and different drawable for disabled and pressed states.


<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false"         android:drawable="@drawable/disabledbluebox" />
    <item android:state_pressed="true" android:drawable="@drawable/pressed_bluebox"/>
    <item android:state_enabled="true" android:drawable="@drawable/bluebox"/>

</selector>


You have to create three different drawables disabledbluebox.xml, bluebox.xml and pressedbluebox.xml.

And this will be used for devices with Sdk less than 21.

 





Comments