我需要在屏幕上显示一个View
下方的弹出窗口PopupWindow
。
我该如何计算所需View
的坐标并将PopupWindow
放置在其下方?代码示例更加受欢迎。谢谢。
我需要在屏幕上显示一个View
下方的弹出窗口PopupWindow
。
我该如何计算所需View
的坐标并将PopupWindow
放置在其下方?代码示例更加受欢迎。谢谢。
定位已经显示的视图非常容易-这是我在代码中使用的方法:
public static Rect locateView(View v)
{
int[] loc_int = new int[2];
if (v == null) return null;
try
{
v.getLocationOnScreen(loc_int);
} catch (NullPointerException npe)
{
//Happens when the view doesn't exist on screen anymore.
return null;
}
Rect location = new Rect();
location.left = loc_int[0];
location.top = loc_int[1];
location.right = location.left + v.getWidth();
location.bottom = location.top + v.getHeight();
return location;
}
您可以使用类似Ernesta建议的代码将弹出窗口固定在相关位置:
popup.showAtLocation(parent, Gravity.TOP|Gravity.LEFT, location.left, location.bottom);
getLeft()
和getBottom()
方法获取视图在布局中的确切位置。您还可以使用getWidth()
和getHeight()
方法了解视图占用的确切空间。如果您想将弹出窗口定位在视图下方。您可以使用setLeft()
和setTop()
方法来定位新的弹出窗口。
要获取主应用程序屏幕的大小,不包括标题和通知栏等内容,请在生成相关屏幕的类中覆盖以下方法(尺寸以像素为单位测量):
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
}
View upperView = ...
int coordinate = upperView.getBottom();
只要高度 - 坐标
对于您的弹出视图足够大,您就可以像这样放置弹出窗口:
PopupWindow popup = new PopupWindow();
Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
popup.showAtLocation(parent, Gravity.CENTER, 0, coordinate);
}
});
在这里,showAtLocation()
方法需要父视图作为参数,还需要提供相对于父视图的重心和偏移位置。