美文网首页
Android倒计时(分钟)

Android倒计时(分钟)

作者: sun_2da7 | 来源:发表于2020-11-19 17:50 被阅读0次

本文通过CountDownTimer来实现倒计时的功能,先上效果图

效果图.gif

1.核心方法就是通过onTick方法来获取时间的改变

public void onTick(long millisUntilFinished) {

        //计时过程显示

        this.millisUntilFinished = millisUntilFinished;

        button.setTextColor(Color.parseColor("#FFFFFF"));

        button.setClickable(false);

        button.setTextSize((float) 11.5);

        DecimalFormat dec = new DecimalFormat("##.##");

        button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");

    }

以下是完整代码

import android.graphics.Color;

import android.os.CountDownTimer;

import android.widget.TextView;

import java.text.DecimalFormat;

public class PeterTimeCountRefresh extends CountDownTimer {

    private TextView button;

    private long millisUntilFinished;

    public PeterTimeCountRefresh(long millisInFuture, long countDownInterval, final TextView button) {

        super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔,要显示的按钮

        this.button = button;

    }

    @Override

    public void onTick(long millisUntilFinished) {//计时过程显示

        this.millisUntilFinished = millisUntilFinished;

        button.setTextColor(Color.parseColor("#FFFFFF"));

        //button.setBackgroundResource(R.drawable.send_code_wait);

        button.setClickable(false);

        button.setTextSize((float) 11.5);

        DecimalFormat dec = new DecimalFormat("##.##");

        button.setText("0" + (int) Math.floor(millisUntilFinished / 60000) + ":" + dec.format((millisUntilFinished % 60000) / 1000) + "s");

    }

    @Override

    public void onFinish() {//计时完毕时触发

        button.setText("刷新");

        button.setTextColor(Color.parseColor("#FFFFFF"));

        // button.setBackgroundResource(R.drawable.send_code);

        button.setClickable(true);

    }

}

2.使用

PeterTimeCountRefresh timer = new PeterTimeCountRefresh(600000, 1000, btnRefresh);

timer.start();

3.最后,在onDestroy中关掉计时器,防止内存泄漏

@Override

    protected void onDestroy() {

        super.onDestroy();

        if (timer != null) {

            timer.cancel();

        }

    }

相关文章

网友评论

      本文标题:Android倒计时(分钟)

      本文链接:https://www.haomeiwen.com/subject/vbyliktx.html