如何为自定义对话框设置圆角? [英] How to set round corners for a custom Dialog?

本文介绍了如何为自定义对话框设置圆角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is code for my custom Dialog:

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:

I followed instructions from other answers by first creating this drawable xml called dialog_bg:

<?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的背景:

Then setting it as the background of the layout_dialog xml:

android:background="@drawable/dialog_bg"

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

But I can't do the final step which is to set the dialog's root view to transparent:

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

因为没有getWindow()函数.

because there's no getWindow() function.

当他们说出根视图时,是否还意味着我在上面的inflate函数中设置为null的那个?

Also when they say root view do they mean the one that I set to null in the inflate function above?

推荐答案

您可以使用材料组件库中包含的 MaterialAlertDialogBu​​ilder :

You can use the MaterialAlertDialogBuilder included in the Material Components library:

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>

这篇关于如何为自定义对话框设置圆角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆