一 View在屏幕上的占用区域、显示区域、绘制区域
二 padding值喝Margin值的获取
根据上图可以知道,padding其实就是代表view的内容与view之间的距离,而Margin值代表的则是view和父view之间的距离
padding和margin的值可以在xml文件中设置,所以只要xml文件被加载,不论View是否被绘制,都可以获取这些值。
三 View的getLeft()、getTop()、getRight()、getBottom()方法
如果你要得到子view的宽高,通过这四个值也可以得到:
childview_width=getRight()-getLeft();
childview_height=getBottom()-getTop();
但是与上面的magin和padding值不同,这四个值需要在完成测量的时候才能获取到值,在测量前调用方法会返回0,
例如:可以在View的post(Runnable)中调用,或者在View的onClick点击事件中调用,或者在Activity(或Fragment)的onPause()方法中调用。在Activity(或Fragment)的onResume()中调用不行,因为View是在onResume()方法执行时进行绘制的,此时调用View可能还没有绘制完,所以返回的是0.
四 MotionEvent里获取坐标的方法
MotionEvent的getX(),getY(),getX(int),getY(int),getRawX(),getRawY(),getRawX(int),getRawY(int)方法:
五 getLocationInWindow()和getLocationOnScreen()
getLocationInWindow是以B为原点的C的坐标
getLocationOnScreen以A为原点。
5.1 getLocationInWindow()
:
getLocationInWindow():一个控件在其父窗口中的坐标位置
使用方法:View.getLocationInWindow(int[] location)
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationOnScreen(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标
5.2 getLocationOnScreen():
一个控件在其整个屏幕上的坐标位置
使用方法:View.getLocationOnScreen(int[] location)
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationOnScreen(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标
六 getGlobalVisibleRect():全局可见区域
View可见部分相对于屏幕的坐标。
代码示例:
Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);
globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();
示意图:
七 getLocalVisibleRect():局部可见区域
View可见部分相对于自身View位置左上角的坐标。
示例代码:
Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);
localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();
示意图:
