1.getLocationInWindow和getLocationOnScreen
①一个控件在其父窗口中的坐标位置
View.getLocationInWindow(int[] location)
一个控件在其整个屏幕上的坐标位置,注意这个值要从屏幕顶端算起,也就是包括了通知栏的高度。
View.getLocationOnScreen(int[] location)
getLocationInWindow是以B为原点的C的坐标
getLocationOnScreen以A为原点。
注意:在Activity的onCreate()方法里获取这些值时,全为0,要等UI控件都加载完了才能获取到。因此在onWindowFocusChanged(boolean hasFocus)中获取为好。
②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];//获取当前位置的纵坐标
③源码
View.getLocationInWindow(int[] location):
/** Computes the coordinates of this view in its window. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order. */