我用倒数计时器实现了5秒倒计时,以下是我的代码:
public class CountDownTimerActivity extends AppCompatActivity {
Button button;
MyCountTimer timer;
boolean isTick = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down_timer);
timer = new MyCountTimer(5*1000,1000);
button = (Button)findViewById(R.id.countdown);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isTick){
timer.start();
isTick = !isTick;
}
}
});
}
class MyCountTimer extends CountDownTimer{
public MyCountTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long l) {
button.setText(l/1000+"秒");
}
@Override
public void onFinish() {
button.setText("Sms Verification Code");
isTick = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
isTick = false;
}
}
但是我发现了一个奇怪的现象,例如我首先点击按钮,它会显示4,3,2,1,有时我再次点击按钮,它可能是5,3,2,1或5,4,2,1.我不知道原因,我期望的结果是5,4,3,2,1。 谁能帮助我?
我想
问题出在
button.setText(l/1000+"秒");
将其更改为
int second = Math.round(l/1000f);
button.setText(second +"秒");
如果有一些延迟或滴答会运行得太早,你会得到l = 3999
,你把它除以 1000,你会得到 3。这就是为什么你会有奇怪的结果。
我使用了Handler而不是使用CountDownTimer来实现倒计时。你可以这样尝试
public class MainActivity extends AppCompatActivity {
private TextView label;
private Handler mTimerHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
label = (TextView) findViewById(R.id.label);
findViewById(R.id.btnStartTimer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTimerHandler = new Handler(getMainLooper());
mTimerHandler.postDelayed(new Timer(MainActivity.this, 5), 1000);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTimerHandler != null) {
mTimerHandler.removeCallbacksAndMessages(null);
mTimerHandler = null;
}
}
private static class Timer implements Runnable {
int count = 1;
int max;
WeakReference<MainActivity> ui;
Timer(@NonNull MainActivity activity, int max) {
this.ui = new WeakReference<>(activity);
this.max = max;
}
@Override
public void run() {
if (count <= max) {
ui.get().label.setText(String.format("%s sec", count++));
ui.get().mTimerHandler.postDelayed(this, 1000);
} else {
ui.get().label.setText("Sms verification completed.");
ui.get().mTimerHandler.removeCallbacks(this);
}
}
}
}
我解决了我的问题,因为倒数计时器不准确,它的公差范围是 1-10ms,所以如果你想 5s 倒计时,你可以在毫秒未来中添加 200 毫秒。 例如:
timer = new MyCountTimer(5200,1000);
@Override
public void onTick(long l) {
button.setText(l/1000+"second");
}
它将显示 5,4,3,2,1