我们可以通过如下的方法获得某个控件在屏幕中的绝对坐标
代码如下:
private int[] mHistoryDisplayButtonLocation; private int mHistoryDisplayButtonLocationX; private int mHistoryDisplayButtonLocationY; mHistoryDisplayButtonLocation = new int[2]; mHistoryDisplayButton.getLocationOnScreen(mHistoryDisplayButtonLocation); mHistoryDisplayButtonLocationX = mHistoryDisplayButtonLocation[0]; mHistoryDisplayButtonLocationY = mHistoryDisplayButtonLocation[1];
如果你把上面这段代码放到onCreate中执行,那么你会发现,打印的结果是0
后来网上找答案,说是定位坐标需要时间。但是,在另一篇文章中看到了真正的解决方法
原来,我们需要把上面得到坐标的操作放到
onWindowFocusChanged 方法中去执行
@Override public void onWindowFocusChanged(boolean hasFocus) { mHistoryDisplayButton.getLocationOnScreen(mHistoryDisplayButtonLocation); mHistoryDisplayButtonLocationX = mHistoryDisplayButtonLocation[0]; mHistoryDisplayButtonLocationY = mHistoryDisplayButtonLocation[1]; super.onWindowFocusChanged(hasFocus); }