Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change long click delay

Tags:

android

view

I am listening for a View's long click events via setOnLongClickListener(). Can I change the long click delay / duration?

like image 590
fhucho Avatar asked Mar 31 '12 18:03

fhucho


3 Answers

This is my way for set duration to long press

private int longClickDuration = 3000;
private boolean isLongPress = false;

numEquipeCheat.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                isLongPress = true;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isLongPress) {
                            Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                            vibrator.vibrate(100);
                            // set your code here
                            // Don't forgot to add <uses-permission android:name="android.permission.VIBRATE" /> to vibrate.
                        }
                    }
                }, longClickDuration);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                isLongPress = false;
            }
            return true;
        }
    });
like image 120
Galoway Avatar answered Oct 27 '22 09:10

Galoway


AFAIK, no. It is hard-wired in the framework via getLongPressTimeout() on ViewConfiguration.

You are welcome to handle your own touch events and define your own "long click" concept. Just be sure that it is not too dramatically different from what the user expects, and most likely the user will expect what all the other apps use, which is the standard 500ms duration.

like image 29
CommonsWare Avatar answered Oct 27 '22 09:10

CommonsWare


I defined an extension function in Kotlin inspired by @Galoway answer:

fun View.setOnVeryLongClickListener(listener: () -> Unit) {
    setOnTouchListener(object : View.OnTouchListener {

        private val longClickDuration = 2000L
        private val handler = Handler()

        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            if (event?.action == MotionEvent.ACTION_DOWN) {
                handler.postDelayed({ listener.invoke() }, longClickDuration)
            } else if (event?.action == MotionEvent.ACTION_UP) {
                handler.removeCallbacksAndMessages(null)
            }
            return true
        }
    })
}

Use it like this:

button.setOnVeryLongClickListener {
    // Do something here
}
like image 34
vovahost Avatar answered Oct 27 '22 08:10

vovahost