getLocationInWindow和getLocationOnScreen的区别

一个控件在其父窗口中的坐标位置

View.getLocationInWindow(int[] location)

一个控件在其整个屏幕上的坐标位置
View.getLocationOnScreen(int[] location)

Alt text

getLocationInWindow是以B为原点的C的坐标
getLocationOnScreen以A为原点。
下面是getLocationOnScreen示例

下面是getLocationOnScreen示例

1
2
3
4
5
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationOnScreen(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标

getLocationOnScreen 的源码

1
2
3
4
5
6
7
8
9
public void getLocationOnScreen(@Size(2) int[] outLocation) {
getLocationInWindow(outLocation);

final AttachInfo info = mAttachInfo;
if (info != null) {
outLocation[0] += info.mWindowLeft;
outLocation[1] += info.mWindowTop;
}
}

下面是getLocationInWindow示例

1
2
3
4
5
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationInWindow(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标

getLocationInWindow 的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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);
}


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]);
}