一 、概述
CardView的繼承關系.png
使用CardView需要單獨引入cardview的support包,具體引入方式:
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
一般布局中會將CardView當做父布局,里面包裹若干個ViewGroup的方式來使用,具體的請看下面的xml布局;
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidwanga.serenitynanian.serenityproject.CardViewActivity">
<android.support.v7.widget.CardView
android:clickable="true"
android:foreground="?attr/selectableItemBackground"
app:cardBackgroundColor="@color/colorAccent"
app:cardCornerRadius="10dp"
app:cardElevation="10dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="200dp"
android:src="@drawable/bg01_02"
android:layout_height="200dp" />
<TextView
android:layout_width="match_parent"
android:text="@string/app_name"
android:textColor="#fff"
android:textSize="24sp"
android:padding="10dp"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:foreground="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
app:cardBackgroundColor="@color/colorPrimary"
app:cardElevation="5dp"
app:cardCornerRadius="10dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:text="Card"
android:textColor="#fff"
android:gravity="center"
android:textSize="24sp"
android:layout_height="100dp" />
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
效果如下:
效果圖.png
二 、CardView常用的擴展屬性
- app:cardBackgroundColor 設置CardView的背景色;
- 2.app:cardCornerRadius 設置CardView的圓角角度;
- 3.app:cardElevation 設置CardView的陰影 ;
- 4.app:cardPreventCornerOverlap 防止CardView的內容和圓角相互交錯;
上面這幾個屬性也可以在代碼中設置,如下:
mCardView = (CardView) findViewById(R.id.cardview);
//設置CradView背景
mCardView.setCardBackgroundColor(ColorStateList.valueOf(getResources().getColor(android.R.color.holo_orange_dark)));
//設置CardView的陰影
mCardView.setCardElevation(3);
//設置圓角
mCardView.setRadius(10);
//設置兼容padding
mCardView.setUseCompatPadding(true);
mCardView.setPreventCornerOverlap(true);
三、設置CardView的點擊效果
在xml中直接設置:
<--在Cardview布局中使用下面兩個屬性-->
android:clickable="true"
android:foreground="?attr/selectableItemBackground"
這個foreground系統提供了多個樣式,常用的就兩個;
- 1.selectableItemBackgroundBorderless 以點擊點為中心進行整體擴散,擴散波紋覆蓋整個布局;
- selectableItemBackground 以點擊中心進行擴散,默認有最大擴散半徑;