35

当我在指定此对话框的布局中使用时,android:layout_width="match_parent"我得到此对话框:

小对话框

我需要更广泛的对话。有任何想法吗?

4

2 回答 2

122

您可以通过抓取Window对话框使用的对象并重置宽度来做到这一点。这是一个简单的例子:

//show the dialog first
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Test Dialog")
        .setMessage("This should expand to the full width")
        .show();
//Grab the window of the dialog, and change the width
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dialog.getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);

这是最终结果。请注意,如果您需要微调某些内容(例如更改背景等),您可以对对话框进行更多样式设置。当我过去不得不这样做时,我通常使用这种方法,并setView()在构建器类上自定义对话框中使用的布局。

例子

于 2012-07-23T14:01:09.917 回答
4

解决此问题的另一种方法是使用:

import android.support.v7.app.AlertDialog;

代替:

import android.app.AlertDialog;
于 2016-11-23T06:49:00.370 回答