Android5.0中向我們介紹了一個全新的控件–CardView,從本質上看,可以將CardView看做是FrameLayout在自身之上添加了圓角和陰影效果。請注意:CardView被包裝為一種布局,並且經常在ListView和RecyclerView的Item布局中,作為一種容器使用。
CardView應該被使用在顯示層次性的內容時;在顯示列表或網格時更應該被選擇,因為這些邊緣可以使得用戶更容易去區分這些內容。
使用CardView
首先,假設你的布局如同下面的形式:
<FrameLayout xmlns:app="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"> <!-- Main Content View --> <RelativeLayout> ... </RelativeLayout> </FrameLayout>
為了使用上面的布局方式來創建一個卡片,首先你需要導入支持的依賴庫(android-support-v7-cardview的jar包)在你的build.gradle文件中。
dependencies {
... compile 'com.android.support:cardview-v7:21.0.2' }
現在將FrameLayout替換為CardView,
<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"> <!-- Main Content View --> <RelativeLayout> ... </RelativeLayout> </android.support.v7.widget.CardView>
就是這樣!使用依賴庫能夠保證你的程序穩定的兼容之前的版本;盡管在AndroidL和之前的Android版本中對其處理方式有所不同。
定制CardView
CardView提供了一個默認的elevation(意為CardView的Z軸陰影)和圓角角度,所以每一個卡片都能夠在不同的設備上保持相同的外觀。然而,你也可以根據自己的需求去定制這些值。
<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" card_view:cardCornerRadius="8dp" card_view:cardElevation="8dp"> <!-- Main Content View --> <RelativeLayout> ... </RelativeLayout> </android.support.v7.widget.CardView>
注意:cardElevation屬性被用來決定陰影的大小以及柔和度,以至於可以逼真的模擬出對於深度效果的描述。
添加波紋點擊效果
默認情況,CardView是不可點擊的,並且沒有任何的觸摸反饋效果。觸摸反饋動畫在用戶點擊CardView時可以給用戶以視覺上的反饋。為了實現這種行為,你必須提供一下屬性:
<android.support.v7.widget.CardView
... android:clickable="true" android:foreground="?android:attr/selectableItemBackground"> ... </android.support.v7.widget.CardView>
使用android:foreground=”?android:attr/selectableItemBackground”可以使CardView點擊產生波紋的效果,有觸摸點向外擴散。
對更早的版本的支持
在AndroidL之前的設備上,CardView為了支持圓角的效果加上了padding,圓角剪裁操作可以算是很昂貴的操作。相似的,對陰影效果來說,在AndroidL之前,也會提供padding去繪制陰影面積,這些內容的padding是和elevation屬性相關的,按照文檔:
padding值為:
左右兩邊的值為:maxCardElevation + (1 - cos45) * cornerRadius
上下兩邊的值為:maxCardElevation * 1.5 + (1 - cos45) * cornerRadius
因此,如果你需要給自己的內容加上padding的話,需要使用新的屬性:card_view:contentPadding
相似的,如果改變CardView的背景,也需要使用新的屬性:card_view:cardBackgroundColor