Remove padding from CardView under Android 5.0

Posted by onicsoft on Thu, 19 Dec 2019 21:39:37 +0100

Today, I encountered a CardView adaptation problem. On Android 5.0 and below, the CardView will have an extra margin. See the following figure for details:

Android 4.2 effects

Maybe you'll think, did you accidentally set the margin? Well, look at the code

<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="title"
        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="Button"
        android:gravity="center"/>

</android.support.v7.widget.CardView>

Moreover, it's good for Android 5.0 and above, such as my android 7.1 red rice.

What's the problem?

In fact, this is a problem of CardView's own processing. If the CardView has a fillet set, in the system under API20, Android 5.0, CardView will not process the fillet, but will add a margin to prevent overlap with the fillet.

How to solve this problem? In fact, it's easy to do. Just use the cardpreventcenteroverlap property of CardView

//The cardpreventcorner overlap property is set to false
app:cardPreventCornerOverlap="false"

What is the effect?

After adding the cardPreventCornerOverlap property

This is to solve the problem of edge distance, but how is the fillet missing?

So if we need to fillet, we need to define a button background shape file ourselves, and set the two fillet radii at the bottom.

Send the Buddha to the West

<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>
In the end, it's out of the hole

Successfully stepped on a pit

                       Welcome to follow my wechat public account, and make progress with me every day!
AntDream

Topics: Android