我试图获得一个CardView显示涟漪效应时,通过设置android:背景属性在活动XML文件中描述这里在android开发人员页面,但它不起作用。没有动画,但是onClick中的方法被调用。我还尝试按照这里的建议创建一个ripple.xml文件,但结果相同。

出现在活动的XML文件中的CardView:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="155dp"
    android:layout_height="230dp"
    android:elevation="4dp"
    android:translationZ="5dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:onClick="showNotices"
    android:background="?android:attr/selectableItemBackground"
    android:id="@+id/notices_card"
    card_view:cardCornerRadius="2dp">

</android.support.v7.widget.CardView> 

我对android开发相对陌生,所以我可能犯了一些明显的错误。


当前回答

如果你正在使用的minSdkVersion应用程序是9级,你可以使用:

android:foreground="?selectableItemBackground"
android:clickable="true"

相反,从第11级开始,你可以使用:

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

从文档:

clickable -定义该视图是否响应单击事件。必须为布尔值,“true”或“false”。 前景-定义在内容上绘制的可绘制对象。这可以用作覆盖。如果重力设置为填充,前景可绘制对象将参与内容的填充。

其他回答

你应该在CardView中添加以下内容:

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

android Cardview控件的Ripple事件:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:foreground="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp" />

我对AppCompat并不满意,所以我编写了自己的CardView并反向移植了waves。这是在Galaxy S上运行的姜饼,所以这绝对是可能的。

要了解更多细节,请查看源代码。

如果有一个根布局,比如RelativeLayout或LinearLayout,它包含了CardView中所有适配器项的组件,你必须在那个根布局中设置background属性。如:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="122dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="4dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/touch_bg"/>
</android.support.v7.widget.CardView>

添加这两个类似的代码工作就像一个魅力的任何视图,如按钮,线性布局,或CardView只要把这两行,看看魔法…

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