Android Touch Event determining duration

前端 未结 3 1810
無奈伤痛
無奈伤痛 2020-12-03 08:47

How does one detect the duration of an Android 2.1 touch event? I would like to respond only if the region has been pressed for say 5 seconds?

相关标签:
3条回答
  • 2020-12-03 09:15
    long eventDuration = event.getEventTime() - event.getDownTime();
    
    0 讨论(0)
  • 2020-12-03 09:15

    You can't use unix timestamps in this case. Android offers it's own time measurement.

    long eventDuration = 
                android.os.SystemClock.elapsedRealtime() 
                - event.getDownTime();
    
    0 讨论(0)
  • 2020-12-03 09:28

    You could try mixing MotionEvent and Runnable/Handler to achieve this.

    Sample code:

    private final Handler handler = new Handler();
    private final Runnable runnable = new Runnable() {
        public void run() {
             checkGlobalVariable();
        }
    };
    
    // Other init stuff etc...
    
    @Override
    public void onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            // Execute your Runnable after 5000 milliseconds = 5 seconds.
            handler.postDelayed(runnable, 5000);
            mBooleanIsPressed = true;
        }
    
        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(mBooleanIsPressed) {
                mBooleanIsPressed = false;
                handler.removeCallbacks(runnable);
            }
        }
    }
    

    Now you only need to check if mBooleanIsPressed is true in the checkGlobalVariable() function.

    One idea I came up with when I was writing this was to use simple timestamps (e.g. System.currentTimeMillis()) to determine the duration between MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP.

    0 讨论(0)
提交回复
热议问题