当我按住按钮时,如何按下按钮的时间

Rea*_*eam 10 time android button

我有一个按钮,我按下它并继续按住它,如果保持时间超过一定的时间间隔它会激发某种意图,我该怎么做呢.谢谢

Har*_*dik 16

试试这个

你可以Touch Listener用来做这件事.

尝试:

Handler handler = new Handler();
    b.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(run, 5000/* OR the amount of time you want */);
                break;

            default:
                handler.removeCallbacks(run);
                break;

            }
            return true;
        }
    });
Run Code Online (Sandbox Code Playgroud)

哪里bview(在你的情况下,它应该按钮)要在其上进行长按.

而且Runnable run是如下

Runnable run = new Runnable() {

    @Override
    public void run() {
        // Your code to run on long click

    }
};
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助...... :)


Dar*_*rio 7

检测[ACTION_DOWN][1][ACTION_UP][2]事件.

按下按钮([ACTION_DOWN][1])时,启动计时器,测量时间......如果计时器超过,则调用Intent.释放按钮时([ACTION_UP][2])停止计时器.

final Timer timer = new Timer();
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        switch ( arg1.getAction() ) {
        case MotionEvent.ACTION_DOWN:
            //start timer
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // invoke intent
                }
            }, 5000); //time out 5s
            return true;
        case MotionEvent.ACTION_UP:
            //stop timer
            timer.cancel();
            return true;
        }
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

按下按钮时,将启动计时器.如果在5秒超时之前释放按钮,则不会发生任何事情,否则将执行您想要的操作.

  • 我也更新了例子,所以我希望我的想法更清楚. (2认同)

Kan*_*mal 5

long lastDown;
long keyPressedDuration ;

button.setOnTouchListener(new OnTouchListener() {
     @Override
     public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
           lastDown = System.currentTimeMillis();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
           keyPressedDuration = System.currentTimeMillis() - lastDown;
        }
     }
  };
Run Code Online (Sandbox Code Playgroud)

  • 我认为这不会执行 OP 要求的操作,即如果 ACTION_DOWN(由于按住)持续了长按持续时间以外的持续时间,则开始操作。 (2认同)