如何从 RecyclerView 获取触摸反馈?

How to get touch feedback from RecyclerView?

我实现了一个 RecyclerView 但我不知道如何获得触摸反馈(它的连锁反应)。

这是我为 onClickListener 所做的:

holder.itemView.setOnClickListener(new OnClickListener(){

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

    });

并且我在 XML 中添加了可点击和可聚焦的功能。这就是回收站视图膨胀的内容:

<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" >

您必须将波纹可绘制对象设置为背景:

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"/>

您可能需要屏蔽可绘制对象:

<?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>

这将在触摸时创建一个简单的灰色波纹(如果您需要更多说明,请点击此处guide)。

在 SDK 版本 21 (Lollipop) 中添加了 RippleDrawable。在 pre-lollipop 上使用 Ripple drawable 会使应用程序崩溃。要么在前棒棒糖设备上使用简单的选择器,要么使用重新创建效果的库。 (GitHub)

更新:您可以使用这段代码轻松获得涟漪效果:

android:background="?attr/selectableItemBackground"

或者如果您不想要矩形遮罩:

android:background="?attr/selectableItemBackgroundBorderless"

这与棒棒糖之前的设备兼容,我们将使用一个简单的选择器。我相信这会在具有深色主题的应用程序中产生浅色涟漪,反之亦然,因此如果您想要自定义彩色涟漪,您仍然需要创建一个涟漪图。

补充一下@Longi的回答:如果你想让你的RecyclerViews的Item有自己的背景,同时有涟漪效果,你可以按照下面的例子来做: recycler_view_item.xml:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/recyclerview_item_background">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/selectableItemBackgroundBorderless">
       ...
    </LinearLayout>
</LinearLayout>

在这个例子中@drawable/recyclerview_item_background是一个九色补丁的png,但是你可以在这里使用任何背景。

就我而言,当我使用 android:background="?attr/selectableItemBackground" 时,RecyclerView Item 的根线性布局确实产生了连锁反应,但是子线性布局的背景重叠从而隐藏了涟漪效应。