在Android中显示AlertDialog时,它会显示在屏幕中央。有没有办法改变它的位置?
在Android中显示AlertDialog时,它会显示在屏幕中央。有没有办法改变它的位置?
在浏览了多篇帖子后,我找到了解决方案。
下面是代码:
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位置的数值是从下往上的。
例如,如果您想将进度对话框向下移动一点,而不是设置精确的像素位置,则只需要执行以下操作:
progressDialog.getWindow().getAttributes().verticalMargin = 0.2F;
dialog.getWindow().setAttributes(wmlp);
在更改gypsicoder的答案中wmlp的值之后,或者在我的测试中wmlp的设置没有生效。<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在从对话框中删除边框和填充方面的回答,使这幅图更加完整。
wmlp.x = 100; //x position wmlp.y = 100;
,你只需要设置 Gravitywmlp.gravity = Gravity.TOP | Gravity.LEFT;
就足够了。 - Ajay Mistry