本文共 2687 字,大约阅读时间需要 8 分钟。
一个控件在其父窗口中的坐标位置
.getLocationInWindow(int[] location)
一个控件在其整个屏幕上的坐标位置
.getLocationOnScreen(int[] location)

getLocationInWindow是以B为原点的C的坐标
getLocationOnScreen以A为原点。
下面是getLocationOnScreen示例
- start = (Button) findViewById(R.id.start);
- int []location=new int[2];
- start.getLocationOnScreen(location);
- int x=location[0];
- int y=location[1];
下面是getLocationInWindow示例
- start = (Button) findViewById(R.id.start);
- int []location=new int[2];
- start.getLocationInWindow(location);
- int x=location[0];
- int y=location[1];
==================================================================================================
附上源代码
==================================================================================================
.getLocationInWindow(int[] location)
-
-
-
-
-
-
-
- public void getLocationInWindow(int[] location) {
- if (location == null || location.length < 2) {
- throw new IllegalArgumentException("location must be an array of two integers");
- }
-
- if (mAttachInfo == null) {
-
- location[0] = location[1] = 0;
- return;
- }
-
- float[] position = mAttachInfo.mTmpTransformLocation;
- position[0] = position[1] = 0.0f;
-
- 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) {
-
- final ViewRootImpl vr = (ViewRootImpl) viewParent;
- position[1] -= vr.mCurScrollY;
- }
-
- location[0] = (int) (position[0] + 0.5f);
- location[1] = (int) (position[1] + 0.5f);
- }
.getLocationOnScreen(int[] location)
-
-
-
-
-
-
-
- public void getLocationOnScreen(int[] location) {
- getLocationInWindow(location);
-
- final AttachInfo info = mAttachInfo;
- if (info != null) {
- location[0] += info.mWindowLeft;
- location[1] += info.mWindowTop;
- }
- }