How to catch double tap events in Android using OnTouchListener

后端 未结 6 1758
孤独总比滥情好
孤独总比滥情好 2020-12-31 08:45

I am trying to catch double-tap events using OnTouchListener. I figure I would set a long for motionEvent.ACTION_DOWN, and a different long for a second motionEvent.ACTION_D

6条回答
  •  抹茶落季
    2020-12-31 09:34

    In your class definition:

    public class main_activity extends Activity
    {
        //variable for counting two successive up-down events
       int clickCount = 0;
        //variable for storing the time of first click
       long startTime;
        //variable for calculating the total time
       long duration;
        //constant for defining the time duration between the click that can be considered as double-tap
       static final int MAX_DURATION = 500;
    }
    

    Then in your class body:

    OnTouchListener MyOnTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch (View v, MotionEvent event)
        {
            switch(event.getAction() & MotionEvent.ACTION_MASK)
            {
            case MotionEvent.ACTION_DOWN:
                startTime = System.currentTimeMillis();
                clickCount++;
                break;
            case MotionEvent.ACTION_UP:
                long time = System.currentTimeMillis() - startTime;
                duration=  duration + time;
                if(clickCount == 2)
                {
                    if(duration<= MAX_DURATION)
                    {
                        Toast.makeText(captureActivity.this, "double tap",Toast.LENGTH_LONG).show();
                    }
                    clickCount = 0;
                    duration = 0;
                    break;             
                }
            }
        return true;    
        }
    }
    

    This was adapted from an answer in: DoubleTap in android by https://stackoverflow.com/users/1395802/karn

提交回复
热议问题