Android 获取触摸点坐标,判断滑动方向,滑动距离,滑动速度

activity 或 fragment 实现接口  View.OnTouchListener

如:public class MyFragment extends Fragment implements View.OnTouchListener{

 

重写实现方法

 

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //继承了Activity的onTouchEvent方法,直接监听点击事件
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //当手指按下的时候
            x1 = event.getX();
            y1 = event.getY();
        }
        if(event.getAction() == MotionEvent.ACTION_MOVE) {
            //当手指移动的时候
            x2 = event.getX();
            y2 = event.getY();
            if(y1 - y2 > 50) {
                Toast.makeText(MyServiceTestActivity.this, "向上滑", Toast.LENGTH_SHORT).show();
            } else if(y2 - y1 > 50) {
                Toast.makeText(MyServiceTestActivity.this, "向下滑", Toast.LENGTH_SHORT).show();
            } else if(x1 - x2 > 50) {
                Toast.makeText(MyServiceTestActivity.this, "向左滑", Toast.LENGTH_SHORT).show();
            } else if(x2 - x1 > 50) {
                Toast.makeText(MyServiceTestActivity.this, "向右滑", Toast.LENGTH_SHORT).show();
            }
        }
        if (event.getAction()==MotionEvent.ACTION_UP){
            Log.i("Lgq","sssssssll离开了lllll==");
//            updview(nowpersion);
        }
        return super.onTouchEvent(event);
//        return false;
    }

view设置监听

slv = (ScrollListenerView)findViewById(R.id.slv);

slv.setOnTouchListener(this);

 

分发二:重写方法

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction()==MotionEvent.ACTION_UP){
        LgqLogutil.e("动啦啦啦啦");
    }
    return super.dispatchTouchEvent(ev);
}

 

滑动速度:放在MotionEvent.ACTION_MOVE里

VelocityTracker mVelocityTracker = VelocityTracker.obtain();

mVelocityTracker.addMovement(ev);

mVelocityTracker.computeCurrentVelocity(1000);

float xVelocity = mVelocityTracker.getXVelocity();//速度
xVelocity = Math.abs(xVelocity);//去绝对值。向左滑,值为负数

获取最多速度

float  sudu;
if (sudu < xVelocity) {
    sudu = xVelocity;
}

 

你可能感兴趣的:(移动开发)