首页 > 解决方案 > 如何为自定义对话框设置圆角?

问题描述

这是我的自定义对话框的代码:

public class DialogBrightness extends AppCompatDialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.layout_dialog, null);
    
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    /*Build and create the dialog here*/
    
    }
}

我按照其他答案的说明首先创建了这个名为 dialog_bg 的可绘制 xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
        <solid
            android:color="#fff5ee"/>
        <corners
            android:radius="30dp" />
        <padding
            android:left="10dp"
            android:top="10dp"
            android:right="10dp"
            android:bottom="10dp" />
</shape>

然后将其设置为layout_dialog xml的背景:

android:background="@drawable/dialog_bg"

但我不能做最后一步,即将对话框的根视图设置为透明:

dialogBrightness.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

因为没有 getWindow() 函数。

此外,当他们说根视图时,他们的意思是我在上面的 inflate 函数中设置为 null 的那个吗?

标签: javaandroidandroid-alertdialogandroid-dialogfragmentmaterial-components-android

解决方案


您可以使用MaterialAlertDialogBuilderMaterial Components 库中包含的:

import androidx.fragment.app.DialogFragment;

public class CustomDialog extends DialogFragment {

    //...

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {


        return  new MaterialAlertDialogBuilder(getActivity(),R.style.MaterialAlertDialog_rounded)
                .setTitle("Title")
                .setMessage("Message")
                .setPositiveButton("OK", null)
                .create();

    }
}

和:

<style name="MaterialAlertDialog_rounded" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded</item>
</style>

<style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
</style>

在此处输入图像描述


推荐阅读