Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to config the response time for LongClick?

Tags:

android

In Android, View.onLongClickListener() takes about 1 sec to treat it as a long click. How can I configure the response time for a long click?

like image 846
user1234817 Avatar asked Dec 28 '22 05:12

user1234817


1 Answers

The default time out is defined by ViewConfiguration.getLongPressTimeout().

You can implement your own long press:

boolean mHasPerformedLongPress;
Runnable mPendingCheckForLongPress;

@Override
public boolean onTouch(final View v, MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_UP:

            if (!mHasPerformedLongPress) {
                    // This is a tap, so remove the longpress check
                    if (mPendingCheckForLongPress != null) {
                        v.removeCallbacks(mPendingCheckForLongPress);
                    }
                // v.performClick();
            }

            break;
        case  MotionEvent.ACTION_DOWN:
            if( mPendingCheckForLongPress == null) {  
                mPendingCheckForLongPress = new Runnable() {
                    public void run() {
                        //do your job
                    }
                };
            }


            mHasPerformedLongPress = false;
            v.postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());

            break;
        case MotionEvent.ACTION_MOVE:
            final int x = (int) event.getX();
            final int y = (int) event.getY();

            // Be lenient about moving outside of buttons
            int slop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
            if ((x < 0 - slop) || (x >= v.getWidth() + slop) ||
                (y < 0 - slop) || (y >= v.getHeight() + slop)) {

                if (mPendingCheckForLongPress != null) {
                    v. removeCallbacks(mPendingCheckForLongPress);
                }
            }
            break;
        default:
            return false;
    }

    return false;
} 
like image 67
Hai Bo Wang Avatar answered Dec 29 '22 19:12

Hai Bo Wang