如何创建对话,这将是完全在水平维度

问题描述:

当我在布局中使用,它指定该对话框android:layout_width="match_parent"我得到这个对话框:如何创建对话,这将是完全在水平维度

small dialog

我需要对话,这将是广泛的。有任何想法吗?

+0

发布你的XML布局代码试图填补父值,而不是匹配父 – rajpara 2012-07-23 13:48:15

+2

@ rajpara'fill_parent'和'match_parent'完全相同(都是值为-1的常量) – Eborbob 2015-07-02 20:50:51

您可以通过抓取对话框使用的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

请记住这可能看起来像s在大屏幕上进行拖拉,例如像平板电脑。 – wsanville 2012-07-23 15:28:18

+1

如果我的类扩展应用程序,我想在那里调用alertdialog会怎么样? – ManishSB 2014-12-20 13:17:57

+1

如果使用DialogFragment,必须在'onStart'方法中完成设置,请参阅http://*.com/questions/23990726/how-to-make-dialogfragment-width-to-fill-parent/26207535 – Eborbob 2015-07-02 21:24:38

另一种方式来解决这个问题是使用:的

import android.support.v7.app.AlertDialog; 

代替:

import android.app.AlertDialog; 
+0

最简单,最快,最好的解决方案。这应该是被接受的答案。 – PerracoLabs 2017-08-12 12:27:07