[英]How do I make a Button which restarts a CountdownTimer, when clicked?
I have a function that has a timer that I want to "restart" every time you click the button. 我有一个带有计时器的函数,每当您单击该按钮时,我都希望它“重新启动”。 I tried doing this but when the button is clicked several times it appears that there are several timers still going on when I only want the one.
我尝试执行此操作,但是当多次单击按钮时,似乎只有几个定时器仍在运行。 How do I fix this?
我该如何解决?
So, onClick => Cancel last timer => Start new timer 因此,onClick =>取消上一个计时器=>启动新计时器
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
CountDownTimer cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
@Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
cdt.cancel();
cdt.start();
}
The problem is that, everytime you call the method "startService(android.view.View view) {}", a new CountDownTimer is created, so the previous CountDownTimer that you created is not the same reference as this one. 问题在于,每次调用方法“ startService(android.view.View view){}”时,都会创建一个新的CountDownTimer,因此之前创建的CountDownTimer与该引用不同。
To solve that, you are going to have to create the CountDownTimer as a class member for your class: 为了解决这个问题,您将必须创建CountDownTimer作为类的类成员:
public YourClass {
private CountDownTimer cdt;
.... (do whatever)....
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
if (cdt == null) {
cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
@Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
} else {
cdt.cancel();
}
cdt.start();
}
Hope that helps you 希望对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.