gpt4 book ai didi

java - Android CountDownTimer - 添加时间导致多个计时器运行

转载 作者:行者123 更新时间:2023-11-30 01:02:04 24 4
gpt4 key购买 nike

我正在尝试让我的计时器在每次按下按钮时增加 5 秒。我了解到我需要取消以前的计时器并创建一个新的计时器以使其按照我想要的方式工作。当我按下按钮一次时,计时器会增加 5 秒,一切正常。当我多次按下按钮时,我的问题就出现了。计时器将在许多不同的计时器之间闪烁,而不是停留在最新的计时器上。每次我按下按钮,另一个计时器就会在显示屏上闪烁。几乎就好像程序没有取消以前的计时器,而是每次都创建一个新的计时器。我真的很感激这方面的帮助。谢谢大家!

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

int scoreTeamA = 0;
String countDownTimer;
long millisUntilFinishedInt = 5000;
long milliseconds;
long seconds;
long totalAddedTime = 0;
TextView text1;

MyCount counter = new MyCount(millisUntilFinishedInt + totalAddedTime,17);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text1=(TextView)findViewById(R.id.team_a_score);
counter.start();
}

public class MyCount extends CountDownTimer {

public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}

@Override
public void onTick(long millisUntilFinished) {

millisUntilFinishedInt = millisUntilFinished;
seconds = millisUntilFinishedInt/1000;
milliseconds = millisUntilFinishedInt-(millisUntilFinishedInt/1000)*1000;
countDownTimer = "TIME: " + seconds + "." + milliseconds ;
text1.setText(countDownTimer);
}

@Override
public void onFinish() {
countDownTimer = "TIME'S UP!";
text1.setText(countDownTimer);
}
}

public void timerCreation (){
counter.cancel();
MyCount counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}

//method that is called when button is pressed
public void threePoints (View v) {
timerCreation();
}
}

最佳答案

改变这个

public void timerCreation (){
counter.cancel();
MyCount counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}

进入这个

public void timerCreation (){
counter.cancel();
counter = new MyCount(millisUntilFinishedInt + 5000,1);
counter.start();
}

对于当前的实现,您正在取消成员变量 counter。然后创建一个同名的局部变量并启动该变量。下次您按下按钮时,您的成员变量 counter 将再次被取消(已经被取消)以创建一个新的 MyCount 对象并启动该对象。这就是为什么您最终会使用多个计时器的原因

关于java - Android CountDownTimer - 添加时间导致多个计时器运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39264549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com