如何检测Android上按下和释放按钮的时间

And*_*son 25 java android pressed timer button

我想启动一个计时器,它在第一次按下按钮时开始,在释放按钮时结束(基本上我想测量按钮按下的时间长度).我将在这两个时间使用System.nanoTime()方法,然后从最后一个中减去初始数字,以获得按住按钮时经过的时间的度量.

(如果您对使用nanoTime()以外的其他方法有任何建议,或者其他一些方法来衡量按钮的按住时间,我也会对这些人开放.)

谢谢!安迪

Nic*_*ick 44

使用OnTouchListener而不是OnClickListener:

// this goes somewhere in your class:
  long lastDown;
  long lastDuration;

  ...

  // this goes wherever you setup your button listener:
  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) {
           lastDuration = System.currentTimeMillis() - lastDown;
        }

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

  • 这种方法需要修改.如果您按下然后在按下状态时按住按钮滑动手指,则释放手指按钮保持按下状态.您还需要添加`MotionEvent.ACTION_CANCEL`来处理这种行为. (2认同)

Pra*_*rge 7

这肯定会奏效:

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            increaseSize();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            resetSize();
        }
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)


Arc*_*pgc 5

  1. 在onTouchListener中启动计时器.
  2. 在onClickListener中停止时间.

计算差异.