获取view在当前窗口内的绝对坐标
view.getLocationInWindow(location);
location:[0,0]
location[0] :x坐标
location[1] :y坐标
android中getLocationInWindow 和 getLocationOnScreen的区别
获取控件在其父窗口的位置
屏幕->窗口->控件
源码:
/**
* Gets the coordinates of this view in the coordinate space of the window
* that contains the view, irrespective of system decorations.
*
* <p>In multi-window mode, the origin of the coordinate space is the
* top left corner of the window that contains the view. In full screen
* mode, the origin is the top left corner of the device screen.
*
* <p>In multiple-screen scenarios, if the app spans multiple screens, the
* coordinate space also spans multiple screens. But if the app is
* restricted to a single screen, the coordinate space includes only the
* screen on which the app is running.
*
* <p>After the method returns, the argument array contains the x and y
* coordinates of the view relative to the view's left and top edges,
* respectively.
*
* @param outLocation A two-element integer array in which the view
* coordinates are stored. The x-coordinate is at index 0; the
* y-coordinate, at index 1.
*/
public void getLocationInWindow(@Size(2) int[] outLocation) {
if (outLocation == null || outLocation.length < 2) {
throw new IllegalArgumentException("outLocation must be an array of two integers");
}
outLocation[0] = 0;
outLocation[1] = 0;
transformFromViewToWindowSpace(outLocation);
}
/** @hide */
public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
if (inOutLocation == null || inOutLocation.length < 2) {
throw new IllegalArgumentException("inOutLocation must be an array of two integers");
}
if (mAttachInfo == null) {
// When the view is not attached to a window, this method does not make sense
inOutLocation[0] = inOutLocation[1] = 0;
return;
}
float position[] = mAttachInfo.mTmpTransformLocation;
position[0] = inOutLocation[0];
position[1] = inOutLocation[1];
if (!hasIdentityMatrix()) {
getMatrix().mapPoints(position);
}
position[0] += mLeft;
position[1] += mTop;
ViewParent viewParent = mParent;
while (viewParent instanceof View) {
final View view = (View) viewParent;
position[0] -= view.mScrollX;
position[1] -= view.mScrollY;
if (!view.hasIdentityMatrix()) {
view.getMatrix().mapPoints(position);
}
position[0] += view.mLeft;
position[1] += view.mTop;
viewParent = view.mParent;
}
if (viewParent instanceof ViewRootImpl) {
// *cough*
final ViewRootImpl vr = (ViewRootImpl) viewParent;
position[1] -= vr.mCurScrollY;
}
inOutLocation[0] = Math.round(position[0]);
inOutLocation[1] = Math.round(position[1]);
}
Android视图定位方法解析
989

被折叠的 条评论
为什么被折叠?



