我有一个简单的滑动动作来LinearLayout View
使用TouchListener
。
当我触摸和移动时,问题是MotionEvent.ACTION_MOVE
不断被调用。
我怎样才能停止MotionEvent.ACTION_MOVE
被叫?
v.setOnTouchListener(null)
不好:返回 false 并且不工作。
我只想MotionEvent.ACTION_MOVE
被叫一次。
private View.OnTouchListener touchEvent = new View.OnTouchListener() {
private float tempX;
private final float BASE_VALUE = 100;
private final boolean LEFT = false;
private final boolean RIGHT = true;
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
tempX = event.getX();
}
if(event.getAction() == MotionEvent.ACTION_MOVE){
if(event.getX() < (tempX + BASE_VALUE)){
changeView(LEFT);
}else if(event.getX() > (tempX + BASE_VALUE)){
changeView(RIGHT);
}
}
它工作不完美。
但是这个实现还不错(这段代码是我的想法)。
编码:
private View.OnTouchListener touchEvent = new View.OnTouchListener() {
private VelocityTracker mVelocityTracker;
private float tempX;
private final int MIN_DISTANCE = 120;
private final int THRESHOLD_VELOCITY = 200;
private final boolean LEFT = false;
private final boolean RIGHT = true;
private MotionEvent cancelEvent = MotionEvent.obtain(100, 100, MotionEvent.ACTION_CANCEL, 0, 0, 0);
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.d(TAG, "Down");
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(event);
tempX = event.getX();
}
if(event.getAction() == MotionEvent.ACTION_MOVE){
mVelocityTracker.addMovement(event);
mVelocityTracker.computeCurrentVelocity(100);
float velocityX = mVelocityTracker.getXVelocity();
if(tempX - event.getX() > MIN_DISTANCE
&& Math.abs(velocityX) > THRESHOLD_VELOCITY){
Log.d(TAG, "LEFT");
changeView(LEFT);
}else if(event.getX() - tempX > MIN_DISTANCE
&& Math.abs(velocityX) > THRESHOLD_VELOCITY){
Log.d(TAG, "RIGHT");
changeView(RIGHT);
}
v.dispatchTouchEvent(cancelEvent);
}