我有一个
ImageView填充我的整个活动.我需要能够检测到4个触摸事件:
>保持(超过400毫秒)
>点击
>向左滑动
>向右滑动
目前我可以使用以下代码检测前两个:
imageView.setOnTouchListener(new View.OnTouchListener() { private Timer timerr = new Timer(); private long LONG_PRESS_TIMEOUT = 400; // TODO: your timeout here private boolean wasLong = false; @Override public boolean onTouch(View v,MotionEvent event) { Log.d(getClass().getName(),"touch event: " + event.toString()); if (event.getAction() == MotionEvent.ACTION_DOWN) { // HOLD DETECTED timerr.schedule(new TimerTask() { @Override public void run() { SlideShow.this.runOnUiThread(new Runnable() { @Override public void run() { },LONG_PRESS_TIMEOUT); return true; } if (event.getAction() == MotionEvent.ACTION_UP) { if (!isPaused && !wasLong) { // CLICK DETECTED timerr.cancel(); timerr = new Timer(); if (!wasLong) { return false; } });
现在我正在尝试使用此问题中的代码来实现向右滑动和向左滑动操作. Android Swipe on List这个问题在于它适用于listview,您可以在其中为整个列表视图实现onTouchListener,并为列表项实现单独的onItemClickListener.虽然只有一个Listener可用,但我不知道如何适应这种情况.
解决方法
手势探测器是要走的路.
或者,
image.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v,MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: x1 = event.getX(); y1 = event.getY(); t1 = System.currentTimeMillis(); return true; case MotionEvent.ACTION_UP: x2 = event.getX(); y2 = event.getY(); t2 = System.currentTimeMillis(); if (x1 == x2 && y1 == y2 && (t2 - t1) < CLICK_DURATION) { Toast.makeText(getActivity(),"Click",Toast.LENGTH_SHORT).show(); } else if ((t2 - t1) >= CLICK_DURATION) { Toast.makeText(getActivity(),"Long click",Toast.LENGTH_SHORT).show(); } else if (x1 > x2) { Toast.makeText(getActivity(),"Left swipe",Toast.LENGTH_SHORT).show(); } else if (x2 > x1) { Toast.makeText(getActivity(),"Right swipe",Toast.LENGTH_SHORT).show(); } return true; } return false; }