繁体   English   中英

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

[英]How to set round corners for a 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:

<?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() function。

另外,当他们说根视图时,他们是指我在上面的膨胀 function 中设置为 null 的那个吗?

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

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>

在此处输入图像描述

我强烈推荐@GabrieleMariotti 的答案,但我在这里写信是想看看你如何以你原来的方式实现。

没有 getWindow() function。

您可以使用requireView()代替:

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

另外,当他们说根视图时,他们是指我在上面的膨胀 function 中设置为 null 的那个吗?

是的。 一般不建议将null作为root参数传递,因为需要root视图来计算当前正在被LayoutInflater膨胀的view的布局参数。 相反,您应该像这样使用它:

View view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_dialog, rootView, false);  

这里,第三个参数是attachToRoot ,它作为false传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM