返回

如何在 BottomSheetDialogFragment 中添加圆角背景?

Android

为 BottomSheetDialogFragment 添加圆角

前言

BottomSheetDialogFragment 是一个广泛用于在应用程序中显示自定义界面的有用控件。然而,它的默认背景是一个带有方形边缘的半透明灰色背景。对于寻求自定义外观的用户来说,为 BottomSheetDialogFragment 添加圆角至关重要。

问题:圆角未显示

许多开发者在尝试使用 XML 资源文件作为背景时遇到圆角未显示的问题。这是因为 BottomSheetDialogFragment 使用默认的半透明灰色背景,会覆盖自定义背景。

解决方案:保持默认半透明背景

为了解决这个问题,我们需要修改对话框窗口的背景,同时保持其默认的半透明灰色背景。这是通过使用 WindowManagerLayoutParams 设置对话框窗口类型来实现的。

WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(getDialog().getWindow().getAttributes());
lp.windowAnimations = R.style.BottomSheetDialogTheme;
getDialog().getWindow().setAttributes(lp);

自定义圆角背景

以下步骤将指导您创建自定义圆角背景:

  1. 创建自定义背景: 创建一个新的 XML 资源文件,并添加以下代码:

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@android:color/transparent" />
        <item>
            <shape android:shape="rectangle">
                <corners android:topRightRadius="35dp" android:topLeftRadius="35dp" />
                <solid android:color="@color/white" />
                <padding android:top="10dp" android:bottom="10dp" android:right="16dp" android:left="16dp" />
            </shape>
        </item>
    </layer-list>
    
  2. 设置背景: 在 onCreateView() 方法中,将自定义背景设置为对话框窗口的背景:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.charge_layout, container, false);
        initChargeLayoutViews();
    
        // 设置自定义背景
        getDialog().getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.custom_background));
    
        return mView;
    }
    

结论

通过遵循这些步骤,您可以为 BottomSheetDialogFragment 添加圆角,同时保持其默认的半透明灰色背景。这将为您的应用程序界面增添一个优雅且定制的外观。

常见问题解答

  1. 为什么我的圆角不显示?

    确保您已正确设置自定义背景并使用 WindowManagerLayoutParams 保持默认半透明背景。

  2. 我可以更改圆角半径吗?

    是的,只需修改 custom_background.xml 文件中 shape 元素的 corners 属性。

  3. 如何更改背景颜色?

    在 shape 元素的 solid 元素中更改 color 属性即可更改背景颜色。

  4. 是否可以在所有设备上显示圆角?

    是的,这些步骤适用于所有支持 BottomSheetDialogFragment 的设备。

  5. 如何添加阴影?

    要添加阴影,请在 shape 元素中使用 elevation 属性。