Android倒计时(分钟)

本文通过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");
    }

其中Math.floor(millisUntilFinished / 60000)是通过毫秒数获取分钟,
dec.format((millisUntilFinished % 60000) / 1000)是对当前毫秒数取余获取出去分钟后的秒数,保留2位

以下是完整代码

package com.shangshaban.zhaopin.utils;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.widget.TextView;

import java.text.DecimalFormat;

/**
 * 作者: 宋正朋 on 2016/6/18.
 * 发送验证码后的倒计时
 */
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.在Activity中的使用

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

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

@Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

OK,搞定!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 第1章 认识JS JavaScript能做什么?1.增强页面动态效果(如:下拉菜单、图片轮播、信息滚动等)2.实现...
    mo默22阅读 1,470评论 0 5
  • 前言 LZ-Says:今天收到转正通知了,内心也就12s开心,随之而来的就是不平不淡。16年10月18号入职,感觉...
    静心Study阅读 1,926评论 0 2
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,801评论 0 13
  • 你有没有过这样的经历? 辛苦工作一整天,身体疲惫不堪,情绪也变得非常低落;或者混在一群人中间时,莫名产生强烈的孤独...
    满懂事的小九阅读 228评论 0 0
  • 七绝 无题 梁间雏燕语呢喃, 素女临窗读信函。 堪恨桑林遮望眼, 清风过处是归帆。
    川伸阅读 619评论 2 5

友情链接更多精彩内容