You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

RecyclerView圆角裁剪失效:子项背景覆盖圆角问题求助

解决RecyclerView圆角被子项背景覆盖的问题

这个问题我之前也碰到过——当RecyclerView设置了圆角背景,但子项有自己的背景色时,子项的背景会“漏”出圆角区域,把RecyclerView的圆角给盖住。下面给你两种靠谱的解决方案:

方案一:给RecyclerView启用轮廓裁剪

Android提供了clipToOutline属性,只要你的RecyclerView背景是支持轮廓的(比如用<shape>定义的圆角drawable),开启这个属性就能让RecyclerView按照背景的形状裁剪所有子视图,完美解决子项背景覆盖圆角的问题。

修改你的RecyclerView布局代码,添加android:clipToOutline="true"

<android.support.v7.widget.RecyclerView
    android:id="@+id/list_notification"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="-30dp"
    android:background="@drawable/rect_bound_bottom_5dp"
    android:clipChildren="true"
    android:clipToOutline="true" <!-- 新增这一行 -->
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tv_popup_title"
    tools:listitem="@layout/item_popover" />

注意事项:

  • clipToOutline只支持矩形、圆角矩形、圆形的背景drawable,如果你的rect_bound_bottom_5dp是用<shape>写的圆角,完全没问题;如果是复杂的自定义drawable,这个方法可能不生效。

方案二:用父布局包裹RecyclerView(兼容性更强)

如果方案一不生效(比如某些旧版本Android或者特殊drawable),可以给RecyclerView套一层父布局,让父布局承担圆角和裁剪的职责,RecyclerView本身设为透明背景:

<!-- 新增的父布局,负责圆角和裁剪 -->
<android.support.constraint.ConstraintLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/rect_bound_bottom_5dp"
    android:clipChildren="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tv_popup_title">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list_notification"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="-30dp"
        android:background="@android:color/transparent" <!-- 设为透明 -->
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/item_popover" />
</android.support.constraint.ConstraintLayout>

这个方法的原理是让父布局的圆角背景裁剪内部的RecyclerView,子项的背景只会在父布局的圆角范围内显示,不管子项是什么背景色(包括你需要的蓝色)都不会影响圆角效果。

为什么之前的方法不行?

你之前只设置了clipChildren="true",这个属性只是限制子View不能超出父View的矩形边界,但不会根据父View的圆角背景去裁剪子View的内容,所以子项的背景会铺满整个矩形区域,盖住了RecyclerView的圆角。上面两种方案都是让父容器(或RecyclerView本身)按照圆角轮廓来裁剪内容,就能达到你要的设计效果了。

内容的提问来源于stack exchange,提问作者tqn

火山引擎 最新活动