波纹效果在 RelativeLayout 中不起作用

Ripple effect does not work in RelativeLayout

我正在尝试在 API 22 上的 RelativeLayout 中实现涟漪效应,但它没有出现。然而,同样的涟漪在 Button.

中起作用

我的 ripple drawable 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#d1c4e9">
    <item android:id="@android:id/mask"
        android:drawable="@android:color/white" />
    <item android:drawable="@drawable/rect"/>
</ripple>

相对布局代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@drawable/ripple">
</RelativeLayout>

在此之后,波纹被设置为 ButtonRelativeLayout 上的背景。按钮上的涟漪效果很好,但根本没有出现在 RelativeLayout 上。

谁能告诉我我做错了什么?

添加此属性 android:clickable="true" 有效。在 Nexus 5

上测试

除了Rahunandan所说的,如果你使用的是appcompat-v7支持库你还需要添加 android:background="?attr/selectableItemBackground".

在我的例子中,涟漪效应在第一次点击后起作用,但对于第一次点击它对我不起作用。已使用 android:state_activated="true" 和 main.xml [=29= 更改背景选择器文件]:clickable="true" 那么它一直都可以正常工作。

selector.xml(在res\drawable\selector.xml下)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="@drawable/card_bg_pressed" android:state_enabled="true" android:state_pressed="true"/>
<item android:state_activated="true" android:drawable="@drawable/card_bg_focused" android:state_enabled="true" android:state_focused="true"/>
<item android:state_activated="true" android:drawable="@drawable/card_bg_selected" android:state_enabled="false" android:state_selected="true"/>
</selector>

活动中_main.xml

 <com.mysample.RecyclingImageView
    android:id="@+id/imageview_overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/selector"
    android:clickable="true"/>

布局中的这个属性。

android:background="?attr/selectableItemBackground"
android:clickable="true"

对我来说,这很有效(API 23 岁及以上)

    android:background="@drawable/your_background"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground"