Android 5.0以下CardView去掉padding

版权声明:本文为博主原创文章,转载请注明出处,谢谢! https://blog.csdn.net/myth13141314/article/details/82903654

今天碰到一个CardView的适配问题,在Android5.0以下的机子上,CardView会多出一个边距,具体看下图:

Android 4.2上的效果
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

猜你喜欢

转载自blog.csdn.net/myth13141314/article/details/82903654
今日推荐