Skip to content Skip to sidebar Skip to footer

How To Detect The Period For Which A Button Is Press In Android

Is there any way i can detect for how long a button is press?? I want to capture the time for which a button is press and act accordingly. So if a user kept pressing the button for

Solution 1:

Use following to determine the touch duration.You can use that in an if statement: event.getEventTime() - event.getDownTime() > 5000 It calculates in ms, which means that for your 5 sec you need this number to be 5000

DON'T USE: android.os.SystemClock.elapsedRealtime()-event.getDownTime() It might work on the simulator, but it won't work on the device! Don't ask me how I know it ;)

Solution 2:

Give the button a View.OnTouchListener. The onTouch method you'll implement will give you access to a MotionEvent. Then, using getFlags(), you'll know when the user starts pressing the button (ACTION_DOWN) and when he stops (ACTION_UP). Simply record the system time when these occur (or as suggested in another answer, getDownTime() will give the time you need, but only when you have the ACTION_UP flag).

Solution 3:

privatelong timeElapsed = 0L; //make this a global variable//tvTouches could be a TextView or Button or other views
    tvTouches.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    timeElapsed = event.getDownTime();
                    Log.d("setOnTouchListener", "ACTION_DOWN at>>>" + event.getDownTime());
                    break;
                case MotionEvent.ACTION_UP:
                    timeElapsed = event.getEventTime() - timeElapsed;
                    Log.d("setOnTouchListener", "ACTION_UP at>>>" + event.getEventTime());
                    Log.d("setOnTouchListener", "Period of time the view is pressed>>>" + timeElapsed);
                    Toast.makeText(getApplicationContext(), "Period of time the view is pressed in milliseconds>>>" + timeElapsed, Toast.LENGTH_SHORT).show();
                    timeElapsed = 0L;
                    //TODO do something when a certain period of time has passedbreak;
                default:
                    break;
            }
            returntrue;
        }
    });

Post a Comment for "How To Detect The Period For Which A Button Is Press In Android"