1、使用CountDownTimer
private void TimerFun(){
final CountDownTimer countDownTimer = new CountDownTimer(60000,1000) {
@Override
public void onTick(long l) {
//倒计时每秒的回调
mainBinding.tvUp.setText(l/1000+"");
}
@Override
public void onFinish() {
//倒计时结束
}
};
countDownTimer.start();
}
2,使用 Handler + Thread
private boolean isOk = true;
private int time = 59;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 0){
mainBinding.tvDown.setText("" + time);
time--;
if(time<=0){
isOk = false;
}
}
};
};
private void TimerFun2(){
new Thread(){
@Override
public void run() {
while(isOk){
try {
Thread.sleep(1000);
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
3、使用属性动画(经过对比,发现属性动画倒计时不准确)
private void TimerFun3(){
ValueAnimator valueAnimator = ValueAnimator.ofInt(60000,0);
valueAnimator.setDuration(60000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (int)(valueAnimator.getAnimatedValue());
mainBinding.tvMiddle.setText(value/1000+"");
}
});
valueAnimator.start();
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章