View滑动
当点击事件传达到View时,系统记下触摸点的坐标,手指移动时系统记下后触摸的坐标并算出偏移量,并通过偏移量来修改View的坐标。
1 layout()方法
public class CustomView extends View
{
public CustomView(Context context)
{
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
private int lastX;
private int lastY;
@Override
public boolean onTouchEvent(MotionEvent event)
{
int x = (int) event.getX();//得到距离父控件左边距
int y = (int) event.getY(); //得到距离父控件顶边距
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
//计算移动的距离
int offsetX = x - lastX;//移动的X轴距离
int offsetY = y - lastY;//移动的Y轴距离
//调用layout方法来重新放置它的位置
layout(getLeft() + offsetX,//当前距离父边距的左边的距离 + 移动的X轴距离
getTop() + offsetY,
getRight() + offsetX,
getBottom() + offsetY);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
2 offsetLeftAndRight(offsetX);和offsetTopAndBottom(offsetY);
在MotionEvent.ACTION_MOVE中可以使用下面写法
该方法可以替换掉layout()方法
3 LayoutParams(改变布局参数)
LinearLayout.LayoutParams用于保存View的布局参数,因此我们可以通过LinearLayout.LayoutParams来改变View的布局参数从而达到改变View位置的效果。
在MotionEvent.ACTION_MOVE中可以使用下面写法
写法一
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();//父控件是什么就用什么布局下的LayoutParams
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
写法二
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();//父控件是什么就用什么布局下的LayoutParams
marginLayoutParams.leftMargin = getLeft() + offsetX;
marginLayoutParams.topMargin = getTop() + offsetY;
setLayoutParams(marginLayoutParams);