如何创建水平维度的对话框

wes*_*t44 35 layout android dialog

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

小对话

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

wsa*_*lle 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);
Run Code Online (Sandbox Code Playgroud)

这是最终结果.请注意,如果您需要对事物进行微调(例如更改背景等),则可以对对话框执行更多样式设置.当我以前必须这样做时,我通常使用此方法,并setView()在构建器类上自定义对话框中使用的布局.

例

  • @h_k你可以删除那些调用`dialog.getWindow()的边.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));` (6认同)
  • 一个问题:为什么这首先是一个该死的痛苦?如果XML的外部布局指出"match_parent"那么它应该就是这样!该死的,谷歌. (5认同)
  • 请记住,这可能在大屏幕上看起来很奇怪,例如平板电脑. (2认同)