2

I have a custom view and I want to detect when a user has been pressing/touching the same spot for over 2 seconds. I have been using an onTouch event to detect when the user first touches the screen and then see if he is still touching the same spot 2 seconds later. However, how do I detect when the user moves his finger to a different spot (different from the spot during ACTION_DOWN) and holds it there for over 2 seconds. My code for the onTouch event is as follows. I tried implementing the same logic on ACTION_MOVE but it hasn't been working properly. How do I detect it if a user touches the screen, moved his finger to a spot and then kept it stationary for over 2 seconds?

Is there any other methods or class that can help me achieve the same thing?

@Override
public boolean onTouchEvent(final MotionEvent event) {
    // MotionEvent object holds X-Y values
    super.onTouchEvent(event);

    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE:
            Log.d("Action", "Move");
            mViewIsPressed = true;
            touchY = event.getY();
            break;

        case MotionEvent.ACTION_DOWN:
            Log.d("Action", "Down");
            String text = "You click at x = " + event.getX() + " and y = " + event.getY();
                Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
                yCoordPrev = event.getRawY();
            runnable = new Runnable() {
                public void run() {
                    //Check if user is still holding down on the view
                    if (mViewIsPressed) {
                        yCoordCurr = event.getRawY();
                        //Check if position that is being held down is the same (or within range) as 2 seconds ago
                        Log.d("YPrev: ",String.valueOf(yCoordPrev));
                        Log.d("YCurr: ",String.valueOf(yCoordCurr));
                        if ((yCoordCurr < yCoordPrev + 10) && (yCoordCurr > yCoordPrev - 10)) {
                            //Do what you want here after 2 seconds of pressing
                            Log.d("Fire: ", "fire");
                        }
                    }
                }
            };

            handler.postDelayed(runnable, 2000);
            mViewIsPressed = true;
            break;

        case MotionEvent.ACTION_UP:
            Log.d("Action", "Up");
            if (mViewIsPressed) {
                mViewIsPressed = false;
                yCoordCurr = event.getY();
                //Cancel the runnable because the user stopped pressing
                handler.removeCallbacks(runnable);
            }
            break;
    }
    invalidate();
    return true;
}
skbrhmn
  • 1,124
  • 1
  • 14
  • 36

0 Answers0