首页 > 解决方案 > 布局背景不会根据 BottomSheet 布局中的可绘制背景进行裁剪

问题描述

我想制作带有圆角的 BottomSheet 的布局,但是设置一个带有圆角半径的 drawable 不会剪辑布局背景。我正在使用一个BottomSheetDialogFragment.

片段_a.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/round_rectangle">
   <!-- other views here -->
</androidx.constraintlayout.widget.ConstraintLayout>

round_rectangle.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"   >
    <solid
        android:color="@android:color/white" />
    <stroke
        android:width="2dp"
        android:color="#C4CDE0" />
    <padding
        android:left="0dp"
        android:right="0dp"
        android:top="0dp"
        android:bottom="0dp" />
    <corners
        android:topLeftRadius="16dp"
        android:topRightRadius="16dp" />
</shape>

当前结果:

未剪裁的布局

试过:

以编程方式使用

view.clipToOutline = true

请帮忙!提前致谢!

标签: androidandroid-constraintlayout

解决方案


圆角的颜色来自底部纸容器的颜色。要确定如何制作透明角,我们需要检查布局。布局检查器确定了我们感兴趣的关键组件:底部工作表本身(id/bottomSheet)及其框架(id/design_bottom_sheet)。

在此处输入图像描述

我们需要将底部工作表框架id/design_bottom_sheet的背景颜色更改为透明以得到我们的圆角。

一旦框架可用,就很容易找到框架。一旦创建了对话框并且片段的创建已经足够远,设置框架背景的一个地方就是自定义BottomSheetDialogFragment的onActivityCreated()。在片段生命周期的这一点上,视图层次结构被实例化。

@Override
public void onActivityCreated(Bundle bundle) {
    super.onActivityCreated(bundle);
    View frameParent = ((View) getDialog().findViewById(R.id.bottomSheet).getParent());
    frameParent.setBackgroundColor(Color.TRANSPARENT);
}

在此处输入图像描述

您也可以只findViewById()为框架本身做一个:

getDialog().findViewById(R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT)

无论哪种方式都取决于对BottomSheetDialogFragment内部结构的了解,因此请选择您喜欢的那个。


推荐阅读