我需要一个计时器来启动任何时候我按下一个按钮(按钮本身),显示自实时按下它已经过了几秒钟。无论何时再次按下,定时器将重置为0并再次开始递增
我知道这不是方法,按钮工作正常,但计时器应该在onCreate?我不确定这应该如何使用按钮
/usr/local/sbin
答案 0 :(得分:1)
试试这个:使用处理程序
long startTime = 0;
long elapsedTime ;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
int hours = minutes / 60;
seconds = seconds % 60;
//textview for displaying time..
timerTextView.setText(String.format("%d:%02d:%02d", hours, minutes, seconds));
timerHandler.postDelayed(this, 1000);
}
};
b.setOnClickListener(new View.OnClickListener() { //b is your button
@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("Stop")) {
elapsedTime = System.currentTimeMillis() - startTime;
timerHandler.removeCallbacks(timerRunnable);
b.setText("Resume");
} else {
startTime = System.currentTimeMillis() - elapsedTime;
timerHandler.postDelayed(timerRunnable, 0);
Calendar cs = Calendar.getInstance();
System.out.println("Current time => " + cs.getTime());
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String formattedDate = df.format(cs.getTime());
timerTextView.setText(formattedDate);
b.setText("Stop");
}
}
});
它将计算经过时间并显示停止后的时间...
答案 1 :(得分:1)
另一种简单的方法是使用Handler
mHandler = new Handler();
点击按钮即可调用updateSec();
方法,以1秒的间隔更新秒
Runnable UpdateRunnable = new Runnable() {
@Override
public void run() {
updateSec();
}
};
public void updateSec() {
mSeconds++;
mHandler.postDelayed(UpdateRunnable, 1000);
}
示例
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSeconds = 0;
updateSec();//it'll update sec variable every second.
}
});
答案 2 :(得分:0)
您可以使用线程:
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.button:
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
count++;
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(count + "");
}
});
}
}
}).start;
break;
}
}
视图必须在主线程上更新,因此您需要使用具有runnable instance作为参数的post()方法。
或者,您也可以使用AsyncTask。