什么是CardView
CardView顧名思義就是一個(gè)卡片型的View,它是在Android5.0引入的一個(gè)控件,作為一個(gè)容器使用,它本身繼承于FrameLayout,可以說它的使用和FrameLayout差不多,也是用來包裹一些子View,只不過它可以添加圓角和陰影的效果,經(jīng)常在ListView或RecyclerView的item布局中作為容器使用,使內(nèi)容看起來更加突出和顯眼。
如何使用CardView
先看下效果,未使用CardView時(shí):

使用CardView時(shí)的效果:

導(dǎo)入依賴
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
布局文件中,使用CardView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:contentPadding="5dp"
app:cardElevation="5dp"
app:cardCornerRadius="5dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:layout_width="150dp"
android:layout_height="100dp"
android:background="@mipmap/book"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginLeft="5dp"
android:padding="5dp"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="特戰(zhàn)先驅(qū)"
android:textSize="16sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="戰(zhàn)爭是血淋淋的,戰(zhàn)爭是實(shí)實(shí)在在的,戰(zhàn)爭中的每一個(gè)軍人都是有血有肉的。本小說恰恰注重于戰(zhàn)術(shù)層面和細(xì)節(jié)問題,通過一個(gè)個(gè)有血有肉的軍人,演繹出一段段可歌可泣的具體的戰(zhàn)爭故事!"
android:textSize="14sp"
android:lines="4"
android:ellipsize="end"
android:layout_marginTop="5dp"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
和使用FrameLayout一樣,直接用CardView作為容器包裹,其中app:contentPadding="5dp"指定了卡片內(nèi)容于邊距的間隔為5dp,app:cardElevation="5dp"指定了卡片陰影的大小為5dp,app:cardCornerRadius="5dp"指定了卡片的圓角大小為5dp。是不是看起來有種卡片的形狀,相比沒有添加CardView,是不是顯得比較好看。
CardView的一些屬性說明
屬性 說明
cardBackgroundColor 卡片的背景顏色
cardCornerRadius 卡片的圓角大小
cardElevation 陰影的大小
cardMaxElevation 陰影最大高度
cardUseCompatPadding 設(shè)置內(nèi)邊距,V21+的版本和之前的版本仍舊具有一樣的計(jì)算方式
cardPreventCornerOverlap 在V20和之前的版本中添加內(nèi)邊距,這個(gè)屬性為了防止內(nèi)容和邊角的重疊
contentPadding 卡片內(nèi)容于邊距的間隔
contentPaddingTop 卡片內(nèi)容與頂部的邊距
contentPaddingBottom 卡片內(nèi)容與底部的邊距
contentPaddingLeft 卡片內(nèi)容與左邊的邊距
contentPaddingRight 卡片內(nèi)容與右邊的邊距
本文對CardView做了簡單的介紹,并演示了它的效果,需要源碼的可以查看: