简体   繁体   中英

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 5 sec i want to detect that 5 sec on android.

Please let me know

Thanks Pranay

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 ;)

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).

    private long 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 passed
                    break;
                default:
                    break;
            }
            return true;
        }
    });

Register a OnTouchListener on the Button. Then in the listener use the MotionEvent:

http://developer.android.com/reference/android/view/MotionEvent.html

Then use the getDownTime() method of the Event:

http://developer.android.com/reference/android/view/MotionEvent.html#getDownTime%28%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM