android 底部 sheet 顶部边缘弯曲

android bottom sheet with curved top edges

我有一个 bottomsheet,其约束布局为 root.How 以弯曲顶部边缘? 试过此代码,但它不起作用。

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/cl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bottom_sheet_bg"
        android:paddingTop="@dimen/dimen_20dp"
        android:paddingBottom="@dimen/dimen_20dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

bottom_sheet_bg

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:topLeftRadius="@dimen/dimen_20dp"
        android:topRightRadius="@dimen/dimen_20dp"/>
    <solid android:color="@color/white" />
</shape>

需要记住的一点是,应用程序程序员创建的视图结构通常由 Android 放入某种类型的视图组外壳中。让我们来看一个简单的应用程序,将主 activity 的背景着色为蓝色,并将弯曲的顶部背景着色为红色。这是为了更好地展示正在发生的事情。

这是来自 Android Studio 的布局检查器的图像:

如您所见,背景可绘制对象的弧形顶部在那里,但角落有白色背景,这是 FrameLayout design_bottom_sheet 的背景。这在您的应用程序中也是如此,但是您的背景和 FrameLayout 的背景颜色都是白色的,因此圆角似乎不存在。它们存在,但被 FrameLayout.

背景的白色掩盖

要解决此问题,您可以搜索 design_bottom_sheet 并将其背景显式更改为透明,但最好通过样式来解决此问题。

在您的样式文件中创建以下内容:

<style name="BottomSheetDialogStyle" parent="Theme.MaterialComponents.DayNight.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/BottomSheetModalStyle</item>
</style>

<style name="BottomSheetModalStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@drawable/bottom_sheet_bg</item>
</style>

(您的风格可能有所不同,但概念仍然适用。)

BottomSheetDialogFragment 中添加以下内容:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_FRAME, R.style.BottomSheetDialogStyle);
}

或者如果您已经定义了 onCreate(),则只需添加 setStyle() 行。此代码将阻止 design_bottom_sheet 绘制背景。

这将显示以下内容:

并在布局检查器中:

将颜色更改为您需要的颜色,但请记住,角落显示的颜色现在将是 FrameLayout.

下显示的任何颜色

好吧,我实现它的方式就是通过可绘制对象。

rounded_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white"/>
    <corners android:topLeftRadius="16dp"
        android:topRightRadius="16dp"/>
</shape>

里面 res/values/styles.xml

 <style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/AppModalStyle</item>
    </style>
    <style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/rounded_dialog</item>
    </style>

和 java/kotlin

里面
final BottomSheetDialog dialog = new BottomSheetDialog(getActivity(), R.style.AppBottomSheetDialogTheme));