2

我使用下面的代码来检测列表视图上的滑动:

SwipeGestureListener.java

import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;

public class SwipeGestureListener implements GestureDetector.OnGestureListener{

    private static final int SWIPE_MIN_DISTANCE = 150;
    private static final int SWIPE_MAX_OFF_PATH = 100;

    private static final int SWIPE_THRESHOLD_VELOCITY = 100;
    protected MotionEvent mLastOnDownEvent = null;
    private static final int SWIPE_THRESHOLD_VELOCITY = 100;

    public SwipeGestureListener(Context context) {
    }

    @Override   
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        if (e1==null)
            e1 = mLastOnDownEvent;
        if (e1==null || e2==null)
            return false;

        float dX = e2.getX()-e1.getX();
        float dY = e2.getY()-e1.getY();

        if (Math.abs(dY)<SWIPE_MAX_OFF_PATH && Math.abs(velocityX)>=SWIPE_THRESHOLD_VELOCITY && Math.abs(dX)>=SWIPE_MIN_DISTANCE ) {
            if (dX>0) {
                Toast.makeText(context, "Right Swipe", Toast.LENGTH_SHORT).show();
            } else{
                Toast.makeText(context, "Left Swipe", Toast.LENGTH_SHORT).show();
            }

            return true;
        }

        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

   @Override
   public boolean onSingleTapUp(MotionEvent e) {
      // TODO Auto-generated method stub
       return false;
   }

    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }


}

我的活动.java

ListView listview = (ListView)findViewById(R.id.song_list_listview);

final GestureDetector gdt = new GestureDetector(this, new SwipeGestureListener(this));
listview.setOnTouchListener(new OnTouchListener(){

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gdt.onTouchEvent(event);
        // TODO Auto-generated method stub
        return false;
    }

});

此代码有效,但它似乎仅在我对列表视图的同一项目执行滑动手势时才有效。

例如,我有项目 1、2 和 3。当我开始在项目 2 上滑动时,正在进行的滑动手势必须在项目 2 布局内并在项目 2 布局上结束,这样手势检测才能工作。

检测列表视图滑动的最佳方法是什么?谢谢!

4

0 回答 0