如何创建一个在水平方向上完整显示的对话框。

35

当我在布局中使用 android:layout_width="match_parent" 来指定这个对话框时,我得到了这个对话框:

小对话框

我需要一个更宽的对话框。有什么想法吗?


请发布您的XML布局代码,并尝试使用fill_parent值而不是match_parent。 - rajpara
2
@rajpara fill_parentmatch_parent 做的事情完全相同(两者的常量值都是-1)。 - Eborbob
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() 自定义对话框中使用的布局。

example


2
请记住,在大屏幕上(例如平板电脑)可能会看起来很奇怪。 - wsanville
1
如果我的类扩展了Application并且我想在其中调用AlertDialog,该怎么办? - ManishSB
1
如果使用DialogFragment,则必须在onStart方法中进行设置,请参见https://dev59.com/7WAg5IYBdhLWcg3wFHqF#26207535。 - Eborbob
5
为什么一开始做这件事就这么麻烦呢?如果XML的外部布局声明为“match_parent”,那它应该完全符合那个标准!该死的,Google。 - Someone Somewhere
6
你可以通过调用 dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); 来移除那些边缘。 - Juan José Melero Gómez
显示剩余2条评论

4
另一种解决方法是使用以下内容:
import android.support.v7.app.AlertDialog;

替代:

import android.app.AlertDialog;

最简单、最快速、最好的解决方案。这应该是被接受的答案。 - PerracoLabs

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