如先前所述,最简单的解决方案是将以下内容之一添加为您的RecyclerView
行的背景:
android:background="?android:attr/selectableItemBackground"
android:background="?attr/selectableItemBackground"
然而,如果您使用此方法遇到问题,或者想更细致地控制颜色,则可以执行以下操作。
自定义波纹效果
本答案以这个简单的Android RecyclerView示例开始。它将看起来像以下图像。
为API 21以下的设备添加选择器
在API 21之前(Android 5.0 Lollipop),点击RecyclerView
项只会更改其背景颜色(没有波纹效果)。这也是我们要做的。如果您仍有使用这些设备的用户,则他们已经习惯了这种行为,所以我们不会过多担心他们。(当然,如果您真的希望为他们提供涟漪效应,也可以使用自定义库。)
右键单击res/drawable
文件夹,选择新建 > Drawable 资源文件。将其命名为custom_ripple
。点击确定,并粘贴以下代码。
custom_ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorAccent" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent" />
</shape>
</item>
</selector>
我在按下状态下使用colorAccent
作为高亮颜色,因为它已经可用,但您可以定义任何颜色。
为API 21+设备添加涟漪效果
右键单击res/drawable
文件夹,然后选择新建 > Drawable 资源文件。再次将其命名为custom_ripple
。这一次不要点击OK。从可用限定符列表中选择版本,然后点击>>按钮并输入平台API级别为21
。现在点击确定并粘贴以下代码。
v21/custom_ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorAccent">
<item
android:id="@android:id/mask"
android:drawable="@android:color/white" />
</ripple>
我再次使用colorAccent
作为波纹颜色,因为它是可用的,但您可以使用任何您想要的颜色。遮罩将波纹效果限制在行布局中。遮罩颜色显然无关紧要,所以我只使用了不透明的白色。
设置为背景
在您的RecyclerView项目的根布局中,将背景设置为我们创建的自定义波纹。
android:background="@drawable/custom_ripple"
在我们开始的示例项目中,它看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/custom_ripple"
android:padding="10dp">
<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
完成
这就是全部内容了。现在您应该能够运行您的项目了。感谢这个答案和这个YouTube视频提供的帮助。
CardView
的特定方面与这个更一般的问题无关。 - Suragch