Android ListView与OnItemClickListener和GestureDetector

前端之家收集整理的这篇文章主要介绍了Android ListView与OnItemClickListener和GestureDetector前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个以下ListActivity:
public class ShowDayActivity extends ListActivity implements OnItemClickListener {
    private GestureDetector gestureDetector;
    private View.OnTouchListener gestureListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.day);
        registerForContextMenu(getListView());

        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v,MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        };

        getListView().setOnItemClickListener(this);
        getListView().setOnTouchListener(gestureListener);
    }

    @SuppressWarnings("static-access")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        ...
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ...
        return super.onContextItemSelected(item);
    }

    Override
    public void onItemClick(AdapterView<?> parent,View v,int pos,long id) {
        editEvent(pos);
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_MAX_OFF_PATH = 250;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;

        @Override
        public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY) {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
               return false;
            }
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("ICS-Calendar","Fling left");
                return true;
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("ICS-Calendar","Fling right");
                return true;
            }

            return false;
        }
    }   
}

listItems上的contextListener(long-click)完美地工作.今天我添加了gestureListener和Detector,它也是这样,但是:

GestureDetector检测到一切都没有了,但是在完成了逻辑之后,会打开上下文菜单,这显然不是我想要的.任何想法我做错了,还是我可以做什么?

解决方法

通常,您需要调用cancelLongPress()方法,并检测到onFling后的所有视图的子项.但是对于AbsListView,这个方法什么也不做:(

但是我已经找到了解决方法:在onFling回调中,处理完所有内容后,为ListView对象执行下一步:

Event cancelEvent = Event.obtain(ev2);
cancelEvent.setAction(MotionEvent.ACTION_UP);
listView.onTouchEvent(cancelEvent);

猜你在找的Android相关文章