108

当我们在 android 中显示 AlertDialog 时,它会显示在屏幕中央。有什么办法可以改变位置吗?

4

4 回答 4

265

在各种帖子中搜索后,我找到了解决方案。

代码贴在下面:

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 位置值是从下到上。

于 2011-05-18T20:56:44.157 回答
16

例如,如果您想将进度对话框向下移动一点,而不是设置确切的像素位置,那么这就足够了:

progressDialog.getWindow().getAttributes().verticalMargin = 0.2F;
于 2012-08-09T12:49:00.220 回答
8

为了使设置来信息效果,我添加了以下代码
dialog.getWindow().setAttributes(wmlp);

在 gypsicoder 的答案中更改 wmlp 的值后,或者 wmlp 的设置在我的测试中没有生效。

于 2013-11-02T12:22:22.813 回答
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 致敬,他的回答是:删除边框,从对话框中填充完成了这张图片。

于 2015-12-10T15:21:50.517 回答