Android 5.0以下CardView去掉padding
今天碰到一個CardView的適配問題,在Android5.0以下的機子上,CardView會多出一個邊距,具體看下圖:

Android 4.2效果
也許你會想,是不是不小心自己設定了邊距?好吧,看看程式碼
<android.support.v7.widget.CardView android:layout_width="200dp" android:layout_height="200dp" app:cardBackgroundColor="@color/white" app:cardCornerRadius="10dp" app:cardElevation="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center|top" android:text="標題" android:textColor="@color/colorPrimary" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="46dp" android:layout_gravity="bottom" android:background="@color/colorPrimary" android:text="按鈕" android:gravity="center"/> </android.support.v7.widget.CardView>
而且,在Android 5.0以上的機子是好的,比如我的Android7.1的紅米上。
問題在哪呢?
實際上,這是CardView本身的一個處理問題,CardView如果設定了圓角,在API20,也就是Android5.0以下的系統中,CardView不會處理圓角,而是會加個邊距來防止和圓角重疊。
那咋解決這個問題呢?其實也好辦,利用CardView的cardPreventCornerOverlap屬性就可以了
//cardPreventCornerOverlap屬性設定為false就可以了 app:cardPreventCornerOverlap="false"
效果是咋樣的呢?

加了cardPreventCornerOverlap屬性以後
這樣是解決了邊距的問題,但是圓角咋不見了呢?
所以如果我們需要圓角的話還需要自己定義一個按鈕的背景shape檔案,設定好下邊的2個圓角半徑就好。
送佛送到西吧
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#3F51B5"/> <corners android:bottomLeftRadius="10dp" android:bottomRightRadius="10dp"/> </shape>

最終效果,出坑了
成功踩完一個坑...
歡迎關注我的微信公眾號,和我一起每天進步一點點!

AntDream