ボタンが最初に押されたときに開始し、離されたときに終了するタイマーを開始したいと思います(基本的に、ボタンが押されている時間を測定したい)。どちらの場合も System.nanoTime() メソッドを使用し、最後の数字から最初の数字を引いて、ボタンが押されている間の経過時間を測定します。
(nanoTime() 以外のものを使用したり、ボタンが押されている時間を測定する他の方法について何か提案があれば、私もそれらを受け入れます。)
ありがとう!アンディ
OnClickListenerの代わりに OnTouchListenerを使用します。
// 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;
}
});
これは間違いなく機能します:
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;
}
});
差を計算します。