Android 5.0以下CardView去掉padding

今天碰到一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值