The idea is to create a Runnable to perform a long click in the future, but this execution may be canceled due to a click or movement.
You should also know when a long click was consumed, and when it is canceled because the fingers move too much. We use initialTouchX & initialTouchY to check if the user leaves the square area of 10 pixels, 5 on each side.
Here is my complete code for delegating Click & LongClick from Cell to ListView for Activity with OnTouchListener :
ClickDelegate delegate; boolean goneFlag = false; float initialTouchX; float initialTouchY; final Handler handler = new Handler(); Runnable mLongPressed = new Runnable() { public void run() { Log.i("TOUCH_EVENT", "Long press!"); if (delegate != null) { goneFlag = delegate.onItemLongClick(index); } else { goneFlag = true; } } }; @OnTouch({R.id.layout}) public boolean onTouch (View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout()); initialTouchX = motionEvent.getRawX(); initialTouchY = motionEvent.getRawY(); return true; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_CANCEL: if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) { handler.removeCallbacks(mLongPressed); return true; } return false; case MotionEvent.ACTION_UP: handler.removeCallbacks(mLongPressed); if (goneFlag || Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) { goneFlag = false; return true; } break; } Log.i("TOUCH_EVENT", "Short press!"); if (delegate != null) { if (delegate.onItemClick(index)) { return false; } } return false; }
ClickDelegate is an interface for sending click events to a handler class, e.g. Activity
public interface ClickDelegate { boolean onItemClick(int position); boolean onItemLongClick(int position); }
And all you need is to implement it in your Activity or parent View if you need to delegate behavior:
public class MyActivity extends Activity implements ClickDelegate { //code... //in some place of you code like onCreate, //you need to set the delegate like this: SomeArrayAdapter.delegate = this; //or: SomeViewHolder.delegate = this; //or: SomeCustomView.delegate = this; @Override public boolean onItemClick(int position) { Object obj = list.get(position); if (obj) { return true; //if you handle click } else { return false; //if not, it could be another event } } @Override public boolean onItemLongClick(int position) { Object obj = list.get(position); if (obj) { return true; //if you handle long click } else { return false; //if not, it a click } } }
IgniteCoders May 16 '18 at 15:58 2018-05-16 15:58
source share