知道按钮按住的时间

时间:2013-03-12 09:20:14

标签: android ontouchlistener

我希望当你在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;
                }

            });

1 个答案:

答案 0 :(得分:2)

已归结为Android Touch Event determining duration

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