如何为自定义对话框设置圆角?

Use*_*163 3 java android android-alertdialog android-dialogfragment material-components-android

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

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*/
    
    }
}
Run Code Online (Sandbox Code Playgroud)

我按照其他答案的说明首先创建了这个称为 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>
Run Code Online (Sandbox Code Playgroud)

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

android:background="@drawable/dialog_bg"
Run Code Online (Sandbox Code Playgroud)

但我无法完成将对话框的根视图设置为透明的最后一步:

dialogBrightness.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Run Code Online (Sandbox Code Playgroud)

因为没有 getWindow() 函数。

另外,当他们说 root view 时,他们的意思是我在上面的 inflate 函数中设置为 null 的那个吗?

Gab*_*tti 7

您可以使用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();

    }
}
Run Code Online (Sandbox Code Playgroud)

和:

<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>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明