轉載至:https://blog.csdn.net/u011150924/article/details/70142514
CardView和RecyclerView一樣是Android5.0以後新出現的控件,伴隨着Material Design設計而誕生。
一、引入CardView
在AS新建項目中需要使用CardView組件,和RecyclerView一樣,需要在Gradle裏面提前加入CardView的
包,直接在Gradle中加入:
compile 'com.android.support:cardview-v7:25.3.1'(CardView版本號與項目裏面V7版本號相同即可)
或者在Library dependence中輸入CardView,選擇V7包下那個即可。
二、爲何使用CardView
CardView是繼承自FramLayout的一個佈局控件,官網裏對CardView的註釋爲:
A FrameLayout with a rounded corner background and shadow.(CardView爲帶圓角和陰影的FramLayout)
以往,我們需要自定義Shape來實現圓角和陰影效果;現在,這些效果集成到了CardView的屬性裏。同時,
CardView應該被使用在顯示層次性的內容時,在顯示列表或網格時更應該被選擇,因爲這些邊緣可以使得用戶
更容易去區分這些內容。
三、CardView屬性
app:cardBackgroundColor 設置背景顏色
app:cardCornerRadius 設置圓角大小
app:cardElevation 設置z軸陰影高度
app:cardMaxElevation 設置z軸最大高度值
app:contentPadding 內容與邊距的間隔
app:contentPaddingLeft 內容與左邊的間隔
app:contentPaddingTop 內容與頂部的間隔
app:contentPaddingRight 內容與右邊的間隔
app:contentPaddingBottom 內容與底部的間隔
app:paddingStart 內容與邊距的間隔起始
app:paddingEnd 內容與邊距的間隔終止
app:cardUseCompatPadding 設置內邊距,在API21及以上版本和之前的版本仍舊具有一樣的計算方式
app:cardPreventConrerOverlap 在API20及以下版本中添加內邊距,這個屬性爲了防止內容和邊角的重疊
注意:CardView中使用android:background設置背景顏色無效。
Ps:多說一句,有時候部分人爲了突出這些屬性是在CardView中使用的,會在CardView內重新命名屬性名,
如:xmlns:card_view="http://schemas.android.com/apk/res-auto",那麼app就會變成card_view,但是
直接使用app不影響什麼,只是一個屬性前綴名的變化。
四、點擊CardView出現波紋(Ripple)效果
在CardView佈局中加入:android:foreground=”?android:attr/selectableItemBackground”即可實現
點擊CardView出現波紋效果。