简体   繁体   English

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

[英]How to detect when button pressed and released on android

I would like to start a timer that begins when a button is first pressed and ends when it is released (basically I want to measure how long a button is held down). 我想启动一个计时器,该计时器在第一次按下按钮时开始,在释放按钮时结束(基本上,我想测量按下按钮的时间)。 I'll be using the System.nanoTime() method at both of those times, then subtract the initial number from the final one to get a measurement for the time elapsed while the button was held down. 我将在这两个时间都使用System.nanoTime()方法,然后从最后一个中减去初始数字,以得到按住该按钮时所经过的时间的度量。

(If you have any suggestions for using something other than nanoTime() or some other way of measuring how long a button is held down, I'm open to those as well.) (如果您对使用nanoTime()以外的方法有任何建议,或者有其他方法可以测量按下按钮的时间,那么我也欢迎那些人。)

Thanks! 谢谢! Andy 安迪

Use OnTouchListener instead of OnClickListener: 使用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;
     }
  });

This will definitely work: 这肯定会起作用:

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;
    }
});
  1. In onTouchListener start the timer. 在onTouchListener中启动计时器。
  2. In onClickListener stop the times. 在onClickListener中停止时间。

calculate the differece. 计算差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM