CardView 設定點選水波紋效果
阿新 • • 發佈:2019-02-17
問題來源
最近用了下RecyclerView,很好用,每個item我設定的是CardView包含一個TextView,
<android.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">
<TextView
android:id="@+id/text_view"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.v7.widget.CardView>
這樣就可以顯示cardview了,問題是給item新增一個selector
解決
1 類似Button直接在drawable下新建個card_selector.xml佈局,然後設定CardView背景:
android:background="@drawable/card_selector"
然,,沒有什麼用。。
給CardView添加個前景:
android:foreground="?android:attr/selectableItemBackground"
這樣就可以了,在5.0以上的裝置上有點選有波紋效果,5.0以下無波紋,只有前景色變化
3 自定義CardView前景
Android-L CardView Visual Touch Feedback
- 設定CardView自定義的前景:
android:foreground="@drawable/card_foreground"
5.0之後
drawable-v21/card_foreground.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
<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"