LongClick event happens too quickly. How can I increase the clicktime required to trigger it?

后端 未结 8 1546
暖寄归人
暖寄归人 2020-12-08 21:26

In an application I\'m working on, I have the requirement that a user must click & hold a component for a period time before a certain action occurs.

I\'m curren

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 22:10

    One method can do it. It's simple to use, easy to configure the time length, on time to trigger the callback.

    public static void setOnLongClickListener(final View view, final View.OnLongClickListener longClickListener, final long delayMillis)
    {
        view.setOnTouchListener(new View.OnTouchListener()
        {
            final Handler handler = new Handler();
            final Runnable runnable = new Runnable()
            {
                @Override
                public void run()
                {
                    longClickListener.onLongClick(view);
                    mRunning = false;
                }
            };
    
            boolean mRunning;
            boolean mOutside;
            RectF mRect = new RectF();
    
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                    {
                        handler.postDelayed(runnable, delayMillis);
                        mRunning = true;
                        mOutside = false;
                        mRect.set(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                        break;
                    }
                    case MotionEvent.ACTION_MOVE:
                        if (!mOutside)
                        {
                            mOutside = !mRect.contains(v.getLeft() + event.getX(), v.getTop() + event.getY());
                            if (mOutside)
                            {
                                handler.removeCallbacks(runnable);
                                mRunning = false;
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    {
                        if (mRunning)
                            v.performClick();
                        handler.removeCallbacks(runnable);
                        mRunning = false;
                        break;
                    }
                    case MotionEvent.ACTION_CANCEL:
                    {
                        handler.removeCallbacks(runnable);
                        mRunning = false;
                        break;
                    }
                }
                return true; // !!!
            }
        });
    }
    

提交回复
热议问题