05 November 2014

Android ripple effect in Lollipop

Just a quick how-to today.

So Google have made a big thing of the new ripple effect in Android Lollipop.
http://android-developers.blogspot.co.uk/2014/10/implementing-material-design-in-your.html

 To my eyes however it wasn't immediately clear how to implement it, particularly if you wanted your app to work in older versions of Android, which almost everyone will.

So the first point to note is android buttons automatically implement the ripple effect if you've got the material theme running. However I mostly used TextViews as buttons with custom drawables for their background and onClick state.

Second I'm not talking about getting ripple working in old versions of Android, just a graceful rollback to a pressed state.

So first create a drawable and a drawable-v21 folder under res, in each add a button_selector.xml

res/drawable/button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Pressed -->
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Selected -->
    <item android:state_selected="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Focus -->
    <item android:state_focused="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Default -->
    <item android:drawable="@color/colorPrimary"/>
</selector>

res/drawable-v21/button_selector.xml
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/accent">
    <!-- Pressed -->
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Selected -->
    <item android:state_selected="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Focus -->
    <item android:state_focused="true" android:drawable="@color/colorPrimaryDark" />
    <!-- Default -->
    <item android:drawable="@color/colorPrimary"/>
</ripple>

now in your activity_main or wherever you need to add a button with a background

<TextView
    android:id="@+id/activity_main_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="@drawable/button_selector"
    android:padding="20dp"
    android:text="Button"/>

You'll notice the ripple xml basically incorporates the same drawables as the selector does, adding on the ripple effect.

No comments: