如何从RecyclerView获得触摸反馈?

Sre*_*ree 9 java android android-listview recycler-adapter android-recyclerview

我实现了一个ReceylerView,我无法弄清楚如何获得触摸反馈(来自它的涟漪效应).

这是我为onClickListener所做的:

holder.itemView.setOnClickListener(new OnClickListener(){

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

    });
Run Code Online (Sandbox Code Playgroud)

我将可点击和可聚焦添加到我的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" >
Run Code Online (Sandbox Code Playgroud)

Lon*_*ngi 30

你必须设置一个波纹drawable作为背景:

android:background="@drawable/ripple"
Run Code Online (Sandbox Code Playgroud)

ripple.xml:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#ffa0a0a0"/>
Run Code Online (Sandbox Code Playgroud)

您可能需要屏蔽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>
Run Code Online (Sandbox Code Playgroud)

这将在触摸时产生简单的灰色波纹(如果您需要更多说明,这里是指南).

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

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

android:background="?attr/selectableItemBackground"
Run Code Online (Sandbox Code Playgroud)

或者如果你不想要矩形面具:

android:background="?attr/selectableItemBackgroundBorderless"
Run Code Online (Sandbox Code Playgroud)

这与棒棒糖前设备兼容,并且我们将使用简单的选择器.我相信这会在黑暗主题的应用程序中产生轻微的涟漪,反之亦然,所以如果你想要一个自定义的彩色波纹,你仍然需要创建一个波纹可绘制.

  • 对于其他人看到此信息,此链接也可能对您有所帮助:https://gist.github.com/AnderWeb/9672f5d81017429fd5fd (4认同)
  • `android:background ="?attr/selectableItemBackground"`完美无缺.这正是我希望在我的`RecyclerView`中显示的简单触摸反馈. (2认同)