在屏幕的任何位置显示AlertDialog

109

在Android中显示AlertDialog时,它会显示在屏幕中央。有没有办法改变它的位置?

4个回答

268

在浏览了多篇帖子后,我找到了解决方案。

下面是代码:

private CharSequence[] items = {"Set as Ringtone", "Set as Alarm"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if(item == 0) {

            } else if(item == 1) {

            } else if(item == 2) {

            }
        }
    });

     AlertDialog dialog = builder.create();
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
     WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();

 wmlp.gravity = Gravity.TOP | Gravity.LEFT;
 wmlp.x = 100;   //x position
 wmlp.y = 100;   //y position

 dialog.show();

这里x位置的数值是从左到右的像素值,而y位置的数值是从下往上的。


2
你也可以创建自定义警报对话框。我最近刚刚这样做了,然后必须获取显示器的宽度和高度,然后根据这些值的百分比设置X和Y,以便布局可以很好地缩放。http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog - Roloc
16
它可以工作,但我不得不添加这一行代码: WMLP.gravity = Gravity.TOP | Gravity.LEFT; 否则,x和y值将被用作从屏幕中心的偏移量。 - BoD
1
只是分享一下经验:上面的代码仅在对话框能完全停留在屏幕上时才有效。例如,如果新的y坐标太大,则对话框将移动到屏幕上仍然显示整个对话框的最低位置。这里的棘手之处在于布局参数的x和y值从那时起不再显示对话框窗口左上角的坐标,并且不能用于计算窗口的相对移动,例如在响应MotionEvent时。 - Nantoka
1
非常好用...但是无需设置 wmlp.x = 100; //x position wmlp.y = 100;,你只需要设置 Gravity wmlp.gravity = Gravity.TOP | Gravity.LEFT; 就足够了。 - Ajay Mistry

17

例如,如果您想将进度对话框向下移动一点,而不是设置精确的像素位置,则只需要执行以下操作:

progressDialog.getWindow().getAttributes().verticalMargin = 0.2F;

我想给重心为中心的警报对话框留出大约10 dp的边距。我可以使用上面的代码吗?如果不行,那么还有其他方法吗? - Aman Verma

8
为了使设置生效,我添加了以下代码:
dialog.getWindow().setAttributes(wmlp); 在更改gypsicoder的答案中wmlp的值之后,或者在我的测试中wmlp的设置没有生效。

1
这些答案将移动AlertDialog的位置,但是显示的对话框的位置也将包括对话框周围的填充。
如果您想摆脱此填充(例如,将对话框放置在屏幕底部),您还需要在styles.xml中覆盖默认的AlertDialog样式,将windowBackground设置为null,如下所示:
<resources>
    <!--  Example app theme - mine uses the below -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:alertDialogTheme">@style/MyDialogTheme</item>
    </style>

    <style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Full width -->
        <item name="android:layout_width">fill_parent</item>

    <!-- Null window background kills surrounding padding -->
        <item name="android:windowBackground">@null</item>
        <item name="android:windowNoTitle">true</item>

     </style>
</resources> 

除了按照被接受的答案所描述的设置Window.LayoutParameters之外。

特别感谢@David Caunt在从对话框中删除边框和填充方面的回答,使这幅图更加完整。


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