Android 如何创建在水平维度上充满的对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11613825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:14:38  来源:igfitidea点击:

How to create dialog which will be full in horizontal dimension

androidlayoutdialog

提问by west44

When I use in layout, which specifies this dialog android:layout_width="match_parent"I get this dialog:

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

small dialog

小对话

I need dialog which will be wider. Any ideas?

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

回答by wsanville

You can do that by grabbing the Windowobject that the dialog uses, and resetting the width. Here's a simple example:

您可以通过抓取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);

Here's the end result. Note that there's a lot more styling you can do to the dialog if you need to fine tune things (like change the background, etc). When I've had to do this in the past, I usually use this method, and customize the layout used in the dialog with setView()on the builder class.

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

example

例子

回答by user2880229

Another way to fix this is to use:

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

import android.support.v7.app.AlertDialog;

instead of:

代替:

import android.app.AlertDialog;