我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。

我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。


当前回答

只要给AlertDialog这个主题

<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>

其他回答

根据Android平台开发人员Dianne Hackborn在这个讨论组的帖子,对话框将窗口的顶层布局宽度和高度设置为WRAP_CONTENT。要使对话框更大,可以将这些参数设置为MATCH_PARENT。

演示代码:

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    Dialog d = adb.setView(new View(this)).create();
    // (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(d.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    d.show();
    d.getWindow().setAttributes(lp);

注意,属性是在对话框显示之后设置的。系统对设置时间很挑剔。(我猜布局引擎必须在对话框第一次显示时设置它们。)

最好通过扩展Theme来实现这一点。对话,那么您就不必玩什么时候调用setAttributes的猜谜游戏了。(尽管让对话框自动采用适当的明暗主题或蜂巢Holo主题需要更多的工作。这可以根据http://developer.android.com/guide/topics/ui/themes.html#SelectATheme来做)

只要给AlertDialog这个主题

<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>

在初始化对话框对象并设置内容视图之后。这样做并享受。

(在这种情况下,我设置90%的宽度和70%的高度,因为宽度90%,它将超过工具栏)

DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
d.getWindow().setLayout(width,height);
d.show();
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

下面的方法对我来说效果不错:

    <style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
        <item name="windowFixedWidthMajor">90%</item>
        <item name="windowFixedWidthMinor">90%</item>
    </style>

(注:windowMinWidthMajor/Minor,如之前的答案所建议的,没有做到这一点。我的对话框不断改变大小取决于内容)

然后:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);