问题
A call to getLocationOnScreen()
or getLocationInWindow()
both give me a top/Y
coordinate that is about ~30px (status/notifications bar's height) too far down. The left/X
coordinate is dead on.
As I hinted above, I believe the difference is because of the status/notification bar... I could be wrong. I think I can solve this if I can determine the size of the notification bar but, I'm having trouble doing just that.
Any help would be greatly appreciated.
回答1:
I ended up solving this issue by determining the height of the status/notification bar like so:
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;
回答2:
Here is how I like to get the status bar height, and adjust the offset:
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);
回答3:
I am having the same problem, try using
offset = myView.GetOffsetY();
and adjust your Y coord by that value, e.g.
coordY -= offset;
The class which offers the ``-method:
class MyView extends View {
public int GetOffsetY() {
int mOffset[] = new int[2];
getLocationOnScreen( mOffset );
return mOffset[1];
}
}
回答4:
This answer does not include how to get the status bar height, but it does explain the behavior of getLocationOnScreen()
and getLocationInWindow()
returning the same value.
In the case of a normal activity (not a dialog) you should expect these two methods to return the same value. A Window lays out underneath (as in z-order not y coordinates) the status bar, so these methods cannot be used to determine the height of the status bar.
https://stackoverflow.com/a/20154562/777165
来源:https://stackoverflow.com/questions/2638342/incorrect-coordinates-from-getlocationonscreen-getlocationinwindow