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

3

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

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()函数。

当他们说根视图时,他们指的是我在上面的填充函数中设置为null的那个吗?

2个回答

7
您可以使用 Material 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>

enter image description here


1
谢谢,这个更简单一些。 - User104163

1
我强烈推荐@GabrieleMariotti的答案,但我在这里写下来看看你如何以自己的方式实现。

没有getWindow()函数。

你可以使用requireView()代替:

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

当他们说根视图时,他们是指我在上面的充气函数中设置为null的那个吗?

是的,就是它。通常不建议将null作为root参数传递,因为需要root视图来计算当前由LayoutInflater充气的view的布局参数。相反,您应该像这样使用:

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

在这里,第三个参数是attachToRoot,被传递为false

什么是rootView? - User104163
rootViewViewGroup 类型的对象(它扩展了 View 类并且是布局和视图容器的基类)。如果 attachToRoot 为 false,则 rootView 用于计算布局参数,否则当前充气的 view 将成为 rootView子级 - cgb_pandey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接