CardView 设置点击水波纹效果

问题来源
最近用了下RecyclerView,很好用,每个item我设置的是CardView包含一个TextView,

.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:id="@+id/cv_item"
    card_view:cardCornerRadius="4dp">

    "@+id/text_view"
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
.support.v7.widget.CardView>

这样就可以显示cardview了,问题是给item添加一个selector

解决
1 类似Button直接在drawable下新建个card_selector.xml布局,然后设置CardView背景:

android:background="@drawable/card_selector"

然,,没有什么用。。

2 google了下,我来到了这里: Android-L CardView Visual Touch Feedback

给CardView添加个前景:

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

这样就可以了,在5.0以上的设备上有点击有波纹效果,5.0以下无波纹,只有前景色变化

3 自定义CardView前景

Android-L CardView Visual Touch Feedback 也给出了方法,分为5.0之前和之后两种设置,因为5.0之前没有ripple,所以5.0之前采用 inset 代替。

  • 设置CardView自定义的前景:
android:foreground="@drawable/card_foreground"
  • 5.0之后

    drawable-v21/card_foreground.xml

"http://schemas.android.com/apk/res/android" 
        android:color="#20000000"
        android:drawable="@drawable/card_foreground_selector" />

drawable-v21/card_foreground_selector.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android" 
        android:color="#20000000"
        android:drawable="@drawable/card_foreground_selector" />
drawable-v21/card_foreground_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#18ffc400"/>
        shape>
    item>
    <item android:state_focused="true" android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#0f000000"/>
        shape>
    item>
selector>

这里写图片描述

  • 5.0之前
    drawable/card_foreground.xml
<inset xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/card_foreground_selector"
    android:insetLeft="2dp"
    android:insetRight="2dp"
    android:insetTop="4dp"
    android:insetBottom="4dp"/>

drawable/card_foreground_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#1838f508"/>
            <corners android:radius="@dimen/card_radius" />
        shape>
    item>
    <item android:state_focused="true" android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#0f000000"/>
            <corners android:radius="@dimen/card_radius" />
        shape>
    item>
selector>

效果:
这里写图片描述

  • 直接设置selector也是可以的:
android:foreground="@drawable/card_foreground_selector"

你可能感兴趣的:(移动开发)