1. 程式人生 > >簡單小巧倒計時工具類 android

簡單小巧倒計時工具類 android

android 簡單小巧倒計時工具類

借鑑前人經驗的基礎上改動

改動內容:

  1. 防止出現-1秒顯示的情況
  2. 防止出現 0秒顯示的情況.在0秒直接自動跳轉

參考部落格地址:
https://blog.csdn.net/z82367825/article/details/47167747

廢話不多說了,先上效果圖

動態廣告跳轉

看到這裡說明有點用,給你個程式碼

// An highlighted block
public class TimeUtil {
//倒計時功能
public interface ITimer {
        public void onCompelete();

        public void onPerSecond(int time);
    }

    Timer timer;
    private ITimer ITimer;
    private int time;

    public TimeUtil(ITimer ITimer, int time) {
        this.ITimer =
ITimer; this.time = time; } public void start() { if (timer == null) { timer = new Timer(); timer.schedule(timerTask, 0, 1000); } } public void stop() { if (timer != null) { timer.cancel(); timer = null; }
} TimerTask timerTask = new TimerTask() { @Override public void run() { //此處改動2 if (time == 0) { handler.sendEmptyMessage(0x02); } else { handler.sendEmptyMessage(0x01); } } }; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x01: //此處改動1 ITimer.onPerSecond(time); --time; break; case 0x02: ITimer.onCompelete(); break; } } }; }

工具類使用示例

        tvLeftSecond.setText("廣告剩餘" + countDownSeconds + "秒");
        timeUtil = new TimeUtil(new TimeUtil.ITimer() {
            @Override
            public void onCompelete() {
                //計時結束
                 timeUtil.stop();
            }

            @Override
            public void onPerSecond(int time) {
                //每過一秒,方法呼叫一次
                tvLeftSecond.setText("廣告剩餘" + time + "秒");
            }
        }, countDownSeconds);
        timeUtil.start();

感覺有用,順手點個贊,收藏一下,有備無患