使用方法:
**LinearLayout mLinearLayout = (LinearLayout)findViewById(R.id.ll);
mLinearLayout.setOnTouchListener(new MoveViewWithFingerTouchListener());**
package com.xxx.view;
import android.annotation.SuppressLint;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
/**
*
* @Title: MoveViewWithFingerTouchListener.java
* @Description: 跟随手指移动的 view
* @ref http://blog.csdn.net/jason0539/article/details/42743531
*/
@SuppressLint("ClickableViewAccessibility")
public class MoveViewWithFingerTouchListener implements View.OnTouchListener {
private int _rawX = 0;
private int _rawY = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
ViewGroup parentView = (ViewGroup) v.getParent();
int parentWidth = parentView.getWidth();
int parentHeight = parentView.getHeight();
// 当前手指触摸位置坐标,用于重新计算
int rawX = (int) event.getRawX();
int rawY = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
// 上次和本次 手指触摸位置坐标 移动的 距离差
int deltaX = rawX - _rawX;
int deltaY = rawY - _rawY;
// 上一次 控件左上角定点的位置坐标
int _x = (int) v.getLeft();
int _y = (int) v.getTop();
// 目标位置 控件左上角定点的位置坐标
int x = deltaX + _x;
int y = deltaY + _y;
//缓冲手指坐标
_rawX = rawX;
_rawY = rawY;
// 左上 边界控制
if (x <= 1) {
x = 1;
}
if (y <= 1) {
y = 1;
}
// 右下边界控制
if (x + v.getWidth() >= parentWidth - 1) {
x = parentWidth - v.getWidth() - 1;
}
if (y + v.getHeight() >= parentHeight - 1) {
y = parentHeight - v.getHeight() - 1;
}
v.layout(x, y, x + v.getWidth(), y + v.getHeight());
break;
case MotionEvent.ACTION_DOWN:
// 初始化首次 手指触摸点的坐标
_rawX = (int) event.getRawX();
_rawY = (int) event.getRawY();
break;
}
return true;
}
}