1. 程式人生 > >Android 獲取觸控點座標,判斷滑動方向,滑動距離

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);