![](/img/trans.png)
[英]How to set the position of a AlertDialog off the screen at top in Android?
[英]How (and when) to move AlertDialog in Android to a new position on the screen?
我需要将Android的AlertDialog移到屏幕上不会掩盖某些活动小部件的位置。 我实际上有两个问题:
我可以在调用dlg.show()之前,使用LayoutParams和wnd.setAttributes()以LEFT | TOP重力设置对话框窗口的位置。 但是,我需要测量对话框的大小才能计算对话框的位置。 可以在显示AlertDialog大小之前对其进行测量吗? 我知道所有测量对话框大小的方法都需要在窗口内检索视图,但是仅调用wnd.getDecorView()会导致随后的dlg.show()抛出异常“在设置内容之前必须调用请求窗口功能” 。 因此,我无法在调用show()之前测量AlertDialog的大小,可以吗?
布置好对话框后,即可确定其大小。 例如,我可以使用wnd.setCallback(),然后在onContentChanged()中将OnGlobalLayoutListener添加到装饰视图中,以便获取onGlobalLayout()通知。 在该通知中,我可以使用两种方法移动对话框:
A.使用LayoutParams和wnd.setAttributes()
B.或使用LayoutParams和mWindowManager.updateViewLayout(wnd.getDecorView(),lp);
对话框已移动,但是...然后将其移回原始位置。 我可以在显示屏上看到它移至新位置,然后移回原始位置。 WTF?!?!?
我试图postDelayed()对话框移动,如果延迟> 300ms,它似乎可以工作。 但是它可以在所有Android设备上使用吗? 我猜不是...所以问题是何时将AlertDialog移到新位置?
有谁知道一种更好的方法来计算警报对话框的大小并将其移动到屏幕上的新位置?
谢谢!
package com.example.alertDialogMove;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.WindowManager;
public class MainActivity extends Activity {
int x;
int y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
x=0;
y=0;
adb();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void adb(){
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle("Um, I am an alert dialog made by rico");
ad.setMessage("To change my position hit the button move me");
ad.setPositiveButton("Click to move me",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
int Min=0;
int Max=200;
x=Min + (int)(Math.random() * ((Max - Min) + 1));
y=Min + (int)(Math.random() * ((Max - Min) + 1));
dialog.cancel();
adb();
}
});
ad.setNegativeButton("Close",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog aD = ad.create();
WindowManager.LayoutParams wmlp = aD.getWindow().getAttributes();
wmlp.gravity = Gravity.TOP | Gravity.LEFT;
wmlp.x = x;
wmlp.y = y;
aD.show();
}
}
您可以像上面那样轻松移动,只需将其解雇并重新放置在新位置即可,我不知道如何获得它的高度;(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.