在屏幕的任何位置显示AlertDialog

时间:2011-03-29 07:04:27

标签: android android-layout android-ui

当我们在android中显示AlertDialog时,它会显示在屏幕的中央。有没有办法改变立场?

4 个答案:

答案 0 :(得分:239)

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

代码发布在下面:

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

答案 1 :(得分:14)

如果您想要进一步向下移动progressdialog,而不是设置exakt像素位置,那么这就足够了:

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

答案 2 :(得分:5)

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

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

答案 3 :(得分:0)

这些答案将移动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大声喊叫,他的回答是:remove border, padding from Dialog完成了这张照片。

相关问题