應用程式經常必須在類似樣式的容器中顯示資料。這些容器經常用於清單,用來保存每個項目的資訊。系統提供 CardView
API,可讓您輕鬆地在平台內顯示樣式一致的資訊卡。這些資訊卡的預設高度會高於其包含的檢視區塊群組,因此系統會在下方繪製陰影。資訊卡可讓您輕鬆包含一組檢視畫面,並同時為容器提供一致的樣式。

新增依附元件
CardView
小工具是 AndroidX 的一部分。若要在專案中使用,請將下列依附元件新增至應用程式模組的 build.gradle
檔案:
Groovy
dependencies { implementation "androidx.cardview:cardview:1.0.0" }
Kotlin
dependencies { implementation("androidx.cardview:cardview:1.0.0") }
建立資訊卡
為了使用 CardView
,請將其新增至版面配置檔案。可用來做為檢視區塊群組,以包含其他檢視畫面。在以下範例中,CardView
含有單一的 TextView
,以便為使用者顯示部分資訊。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >
<!-- A CardView that contains a TextView -->
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="4dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.cardview.widget.CardView>
</LinearLayout>
資訊卡會以預設高度繪製到畫面上,造成系統於其下方繪製陰影。您可透過 card_view:cardElevation
屬性為資訊卡提供自訂高度。如此便能繪製高度較高的較深陰影,而高度越低,陰影就會越淺。CardView
在 Android 5.0 (API 級別 21) 以上版本上採用實際高度和動態陰影,並在先前版本上重新採用程式輔助陰影實作。
請使用下列屬性自訂 CardView
小工具的外觀:
- 若要設定版面配置的圓角半徑,請使用
card_view:cardCornerRadius
屬性。 - 若要設定程式碼中的圓角半徑,請使用
CardView.setRadius
方法。 - 若要設定資訊卡的背景顏色,請使用
card_view:cardBackgroundColor
屬性。