14

I'm a bit lost about how to properly use Ripple Drawable.

Let's say I have this drawable :

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

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

So it is a plain white background which changes to a light blue when it is focused or pressed.

How can I get the same colors but with a ripple effect ? I think I need to use a mask to prevent it from getting outside the bounds of the view ?

Stephane Mathis
  • 6,542
  • 6
  • 43
  • 69

2 Answers2

33

Forgot to answer my own question.

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_shortAnimTime"
   android:color="@color/my_color" >

   <item android:id="@android:id/mask">
       <shape android:shape="rectangle" >
           <solid android:color="@android:color/holo_green_light" />
       </shape>
    </item>

</ripple>

The color in the item with the id "mask" is not displayed. It is used to tell the shape and bounds of the ripple effect. Without it, it can go outside the bounds of the view.

Stephane Mathis
  • 6,542
  • 6
  • 43
  • 69
  • thanks man! saved me here-> http://stackoverflow.com/questions/43531552/how-do-i-change-the-solid-color-of-a-ripple-drawable#autocomment74148081 – reidisaki Apr 21 '17 at 16:44
  • so that means we can set the color of the shape which is under the `mask` id to whatever color we want and it won't be visible? Did I get it right ? – amira Dec 07 '18 at 12:22
25

RippleDrawable is already a StateListDrawable (ie selector) - so you can just use a ripple drawable as your background (with a default state) - something like this:

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

the mask piece bounds the ripple (and, in reality, the above snippet, minus the colors and the last android:drawable which sets the non-pressed background) is the default list selector used in lollipop.

ahmedre
  • 1,684
  • 1
  • 14
  • 18