**轉載請注明本文出自Cym的博客([http://blog.csdn.net/cym492224103](http://blog.csdn.net/cym492224103)**),謝謝支持!**
**
**
前言
CardView顧名思義,就是想卡片一樣的控件,如圖:

Android 5.0之前,我們有兩種方案做出這種效果:
1.通過設置背景圖
2.設置配置Shape文件
而現在我們需要麻煩美工MM,也不需要配置麻煩的Shape文件,只需要簡單的設置幾個屬性即可,那就是用我們CardView
CardView
[CardView](http://developer.android.com/reference/android/support/v7/widget/CardView.html)繼承了[FrameLayout](http://developer.android.com/reference/android/widget/FrameLayout.html)類,并讓你在里面的卡片中(顯示)有跨平臺一致性的外觀。[CardView](http://developer.android.com/reference/android/support/v7/widget/CardView.html)控件可以有陰影和圓角(效果)。
要創建具有陰影效果的卡片,可以使用card_view:cardElevation屬性。[CardView](http://developer.android.com/reference/android/support/v7/widget/CardView.html)會在Android5.0(API級別21)以上的系統中使用真實高程(elevation)和動態陰影,(而)在較低的系統版本中會回落到程序式的陰影效果顯示。欲了解更多信息,請參閱[Maintaining Compatibility(保持兼容性)](http://blog.csdn.net/bbld_/article/details/40634829)。
使用這些屬性來定制[CardView](http://developer.android.com/reference/android/support/v7/widget/CardView.html)控件的外觀:
在布局中設置圓角半徑,使用card_view:cardCornerRadius屬性
在代碼中設置圓角半徑,使用CardView.setRadius方法
要設置一個卡片的背景顏色,使用card_view:cardBackgroundColor屬性
為了讓大家更好理解并使用本人所講的知識點,本次CardView作為item添加到[RecyclerView](http://blog.csdn.net/cym492224103/article/details/41719497)中。
使用步驟:
1.導入/sdk/extras/android/support/v7/cardview/libs/android-support-v7-cardview.jar?
2.把/sdk/extras/android/support/v7/cardview作為Library工程引用到工程
3.修改下item的layout
原有的xml
~~~
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textViewSample"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp"
android:padding="30dp"
android:fontFamily="sans-serif-light"
tools:text="Sample text"
/>
</LinearLayout>
~~~
修改后的xml
~~~
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView
android:id="@+id/textViewSample"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fontFamily="sans-serif-light"
android:padding="30dp"
android:textSize="20sp" />
</android.support.v7.widget.CardView>
~~~
哦了~!趕快去試試吧~!
- 前言
- ym—— Android 5.0學習之創建模擬器
- ym—— Android 5.0學習之使用Material主題
- ym—— Android 5.0學習之使用Palette
- ym—— Android 5.0學習之AnimatedVectorDrawable
- ym—— Android 5.0學習之ListView升級版RecyclerView
- ym—— Android 5.0學習之CardView
- ym—— Android 5.0學習之Activity過渡動畫
- ym—— Android 5.0學習之定義陰影
- ym—— Android 5.0學習之動畫
- ym—— Android 5.0學習之Tinting和Clipping
- ym—— Android 5.0學習之感想篇(含Demo)