【发布时间】:2011-02-07 23:05:52
【问题描述】:
对getLocationOnScreen() 或getLocationInWindow() 的调用都会给我一个top/Y 坐标,该坐标大约是~30px(状态/通知栏的高度)太低了。 left/X 坐标已死。
正如我上面所暗示的,我相信差异是因为状态/通知栏......我可能是错的。如果我可以确定通知栏的大小,我想我可以解决这个问题,但是我无法做到这一点。
任何帮助将不胜感激。
【问题讨论】:
对getLocationOnScreen() 或getLocationInWindow() 的调用都会给我一个top/Y 坐标,该坐标大约是~30px(状态/通知栏的高度)太低了。 left/X 坐标已死。
正如我上面所暗示的,我相信差异是因为状态/通知栏......我可能是错的。如果我可以确定通知栏的大小,我想我可以解决这个问题,但是我无法做到这一点。
任何帮助将不胜感激。
【问题讨论】:
我最终通过确定状态/通知栏的高度解决了这个问题,如下所示:
View globalView = ...; // the main view of my activity/application
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
int topOffset = dm.heightPixels - globalView.getMeasuredHeight();
View tempView = ...; // the view you'd like to locate
int[] loc = new int[2];
tempView.getLocationOnScreen(loc);
final int y = loc[1] - topOffset;
【讨论】:
int [] locInWindow = new int [2]; globalView.getLocationInWindow(locInWindow); topOffset = locInWindow[1]; //通过获取globalView的Y坐标计算topOffset
我喜欢这样获取状态栏高度,并调整偏移量:
final int[] location = new int[2];
anchor.getLocationInWindow(location); // Includes offset from status bar, *dumb*
Rect anchorRect = new Rect(location[0], location[1],
location[0] + anchor.getWidth(), location[1] + anchor.getHeight());
anchor.getRootView().findViewById(android.R.id.content).getLocationInWindow(location);
int windowTopOffset = location[1];
anchorRect.offset(0, -windowTopOffset);
【讨论】:
我也有同样的问题,试试看
offset = myView.GetOffsetY();
并按该值调整您的 Y 坐标,例如
coordY -= offset;
提供 ``-method 的类:
class MyView extends View {
public int GetOffsetY() {
int mOffset[] = new int[2];
getLocationOnScreen( mOffset );
return mOffset[1];
}
}
【讨论】:
此答案不包括如何获取状态栏高度,但确实解释了 getLocationOnScreen() 和 getLocationInWindow() 返回相同值的行为。
在正常活动(不是对话框)的情况下,您应该期望这两种方法返回相同的值。窗口位于状态栏下方(如 z 顺序而非 y 坐标),因此这些方法不能用于确定状态栏的高度。
【讨论】:
正如@ThammeGowda 所说,正确答案会在显示键盘时给出不正确的位置,但您仍然需要计算操作栏的顶部偏移量,所以直接获取操作栏大小
fun View.getPosition(): Point {
val tv = TypedValue()
if (context.theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
val actionBarHeight =
TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
val loc = IntArray(2).apply { getLocationInWindow(this) }
val newY = loc[1] - actionBarHeight - (measuredHeight / 2) // to get the position in the middle of the view
return Point(loc[0], newY)
}
return Point(0,0)
}
【讨论】: