前言
CardView一般用於需要顯示陰影效果的UI,此外CardView還提供了圓角的功能。(嘿嘿,這東西還能直接設置成圓形,可以簡單的弄成圓形View)。CardView其實本身是使用FrameLayout 幀布局,所以它其實還是一個布局。
引用
CardView未在androidx全家桶套餐中,需要你自己添加
implementation 'androidx.cardview:cardview:1.0.0'
一個簡單的使用Demo
xml
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity"> <androidx.cardview.widget.CardView android:id="@+id/card_view" android:layout_width="100dp" android:layout_height="100dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"> <TextView android:id="@+id/content1" android:text="內容" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent"/> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout>
效果圖:

Api詳解
設置背景顏色
注意
1.View自帶原本的屬性android:background="" 已經沒有效果了,被下面的方法替代了
2.下面提供的api只能設置顏色不能設置圖片
xml
app:cardBackgroundColor="@android:color/holo_blue_bright"
java
mCardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
效果圖:

設置圓角
xml
app:cardCornerRadius="50dp"
java
mCardView.setRadius(20);
效果圖:

設置陰影效果
xml
app:cardElevation="30dp"
java
mCardView.setCardElevation(10);
設置最大陰影
xml
app:cardMaxElevation="100dp"
java
mCardView.setMaxCardElevation(10);
設置內邊距
xml
app:contentPadding="10dp"
app:contentPaddingTop="10dp"
app:contentPaddingBottom="10dp"
app:contentPaddingLeft="10dp"
app:contentPaddingRight="10dp"
java
mCardView.setPadding(10,10,10,10);
自動設置內邊距,讓內容不會與圓角重疊
app:cardPreventCornerOverlap="true"
兼容模式
個別機型(說的就是你,喜歡瞎搞的華為)或者Android版本使用CardView沒有效果,可能需要開啟兼容模式
app:cardUseCompatPadding="true"
點子
實現一個圓形的CardView
因為,在onCreate生命周期里,CardView並沒有測量繪制完成,所以我們需要等CardView運行完全部繪制工作后在執行設置圓角的代碼。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mCardView = findViewById(R.id.card_view); mCardView.post(new Runnable() { @Override public void run() { mCardView.setRadius(mCardView.getWidth()/2); } }); }
End
app:cardUseCompatPadding="true"
