1

我希望当您在 3 秒内按住按钮时做某事,我尝试使用上面的代码,但它仅在我停止按住时才起作用,而不是在按住期间。我应该实现一个监听器还是类似的东西?

finishPushing = true;
.
.
.    

button.setOnTouchListener(new OnTouchListener()
            {

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

                    if(android.os.SystemClock.elapsedRealtime() - event.getDownTime() > 3000 && (event.getPointerCount() == 1) && finishPushing)
                    {
                        // Do something                     

                        finishPushing = false;
                    }
                    else{
                        finishPushing = true;
                    }
                    return false;
                }

            });
4

1 回答 1

3

借助Android Touch Event 确定持续时间已解决

        button.setOnTouchListener(new OnTouchListener()
        {
            private final Handler handler = new Handler();
            private final Runnable runnable = new Runnable() {
                public void run() {
                     if(mBooleanIsPressed)
                     {
                         // do whatever
                     }
                }
            };


            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    // Execute your Runnable after 5000 milliseconds = 5 seconds.
//After this 5secs it will check if is pressed
                    handler.postDelayed(runnable, 5000);    
                    mBooleanIsPressed = true;               
                }

                if(event.getAction() == MotionEvent.ACTION_UP) {
                    if(mBooleanIsPressed) {
                        mBooleanIsPressed = false;
                        handler.removeCallbacks(runnable);
                    }
                }
                return false;
            }
        });
于 2013-03-12T10:01:41.523 回答