view的位置参数
view的位置主要由它的四个顶点来决定的,分别对应view的四个属性:top、left、right、bottom,在layout(int left,int top,int right,bottom)时,设置这四个属性的值
1、view提供一些方法获取自身属性的值
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
- left = getLeft() = layoutParams.leftMargin + 父布局的PaddingLeft
- top= getTop() = layoutParams.topMargin + 父布局的PaddingTop
- right = getRight() = layoutParams.rightMargin + 父布局的PaddingRight
- bottom= getBottom() = layoutParams.bottomMargin + 父布局的PaddingBottom
从android3.0开始,View增加了额外的几个参数: x、y、translationX 和 translationY,其中x和y是View的左上角的坐标,而translationX和translationY是view左上角相对与父容器的偏移量。这几个参数也是相对于父容器的坐标,这几个的参数的换算关系如下
- x = left + translationX;
- y= top + translationY;
需要注意的是View在动画平移的过程中,top 和 left 表示的是原始左上角的位置信息,其值并不会发生改变,此时发生改变的是x、y、translationX和translationY这四个参数
这里引用一篇博客对x、y、translationX和translationY的详解
http://blog.csdn.net/wxv111/article/details/50901199
1.2 layout()方法详解
当调用layout(int left,int top,int right,int bottom)方法改变View的位置时,改变的只是view的mLeft,mTop,mRight,mBottom的值,当父布局刷新时,会重新计算子View的mLeft,mTop,mRight,mBottom的值,这就会导致view重新回到原来的位置。所以在改变view的位置时最好改变其Margin的值,以防止父布局刷新时view回到原来的位置。
2、MotionEvent提供的方法
- getX(): 获取点击事件距离控件左边的距离
- getY(): 获取点击事件距离控件顶边的距离
- getRawX(): 获取点击事件距离整个屏幕左边的距离
- getRawY(): 获取点击事件距离整个屏幕顶边的距离