Search code examples
javaandroidandroid-listviewandroid-recyclerview

How to get touch feedback from RecyclerView?


I implemented a RecyclerView and I can't figure out how to get touch feedback (the ripple effect from it).

Here is what i did for the onClickListener:

holder.itemView.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            //start Intent
        }

    });

And I added both clickable and focusable to my XML. This is what the recycler view inflates:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:padding="4dp" >

Solution

  • You have to set a ripple drawable as the background:

    android:background="@drawable/ripple"
    

    ripple.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="#ffa0a0a0"/>
    

    You may need to mask the drawable:

    <?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="#ffa0a0a0">
        <item android:id="@android:id/mask">
            <shape android:shape="rectangle">
                <solid android:color="#ffa0a0a0"/>
            </shape>
        </item>
    </ripple>
    

    This will create a simple grey ripple upon touch (here's a guide if you need more instructions).

    RippleDrawable was added in SDK version 21 (Lollipop). Using Ripple drawable on pre-lollipop will crash the app. Either use a simple selector on pre-lollipop devices or use libraries that recreate the effect. (GitHub)

    UPDATE: You can get the ripple effect easily with this piece of code:

    android:background="?attr/selectableItemBackground"
    

    or if you don't want the rectangle mask:

    android:background="?attr/selectableItemBackgroundBorderless"
    

    This is compatible with pre-lollipop devices and will us a simple selector. I believe this will create light ripples in apps with dark theme and vice versa, so if you want a custom colored ripple you will still need to create a ripple drawable.