您的位置:首页 > 移动开发 > Android开发

Android获取View在屏幕中的位置

2013-12-11 15:00 691 查看



public final boolean getLocalVisibleRect (Rect r)
 返回一个填充的的rect对象,View的大小,left,top取值都为0.


public final boolean getGlobalVisibleRect (Rect r)获取全局坐标系的一个视图区域,返回一个填充的对象;改rect是基于整个屏幕的。


public void getLocationOnScreen (int[] location)计算该视图在全局坐标系中的x,y值,这个值是从屏幕顶端算起,包含了通知栏的高度。


public void getLocationInWindow (int[] location)计算该视图在他所在的window的x,y值,(获取窗口内的绝对坐标,这个怎么理解?跟上面的getLoactionOnScreen有什么却别?)


public final int getLeft ()


public final int getRight ()


public final int getBottom()


public final int getTop()

上面四个是获取相对于他在父view里的坐标。

※注:如果是在Activity的onCreate()回调里输出上面哪些参数,全为0,必须等所有的UI控件都加载完才能获取到这些。这个详细原因我也不太清楚。

测试代码(参数传入下图的Button控件):
private boolean isViewCovered(final View view){

View currentView = view;
Rect currentViewRect = new Rect();

int[] a = new int[2];
int[] b = new int[2];

boolean partVisible = currentView.getGlobalVisibleRect(currentViewRect);
Log.d(TAG, " "+partVisible +" "+currentViewRect.top+" "+currentViewRect.left+" "+currentViewRect.right+" "+currentViewRect.bottom );
currentView.getLocalVisibleRect(currentViewRect);
Log.d(TAG, currentViewRect.top+" "+currentViewRect.left+" "+currentViewRect.right+" "+currentViewRect.bottom );
currentView.getLocationOnScreen(a);
Log.d(TAG, a[0]+" "+a[1] );
currentView.getLocationInWindow(b);
Log.d(TAG, b[0]+" "+b[1] );

return false;
}


界面:



测试输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息