计时器Chronometer

要实现计时器, 我们一般使用Timer + Handler, 或是直接Handler.postDelay.
如果是倒计时, 可以使用CountDownTimer:

  1. Timer
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
         public void run() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        //
                    }
                });
         }
   }, 0, 1000);
  1. Handler.postDelay
  final Handler handler = new Handler();
  handler.postDelayed(new Runnable() {
        @Override
        public void run() {
             ...
             handler.postDelayed(this, 1000);
        }
   }, 1000);
  1. CountDownTimer
    this.countDownTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long time) {
                //计时中
            }
            
            @Override
            public void onFinish() {
                //finish
            }
        };

其实, 还有一种更方便的方式.

  1. Chronometer
    Chronometer是专门用做计时的控件, 继承自TextView.

用法简单:
getBase():起始时间
setBase(long base):设置计时器的起始时间
start():开始计时
stop():停止计时
setFormat(String format):display this string, with the first "%s" replaced by the current timer value。
setOnChronometerTickListener(OnChronometerTickListener listener):计时器监听

xml中直接使用

  

然后在代码中开始启动计时就可以了

  Chronometer chronometer = findViewById(R.id.chronometer);
  // chronometer.setFormat("elapsed : %s");
  chronometer.setBase(SystemClock.elapsedRealtime());
  chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                LogUtils.d("-----" + chronometer.getBase());
            }
        });
  chronometer.start();

大概看下实现方式, 也是使用Handler.postDelay方式实现的

  public void start() {
        mStarted = true;
        updateRunning();
    }

  private void updateRunning() {
        boolean running = mVisible && mStarted && isShown();
        if (running != mRunning) {
            if (running) {
                updateText(SystemClock.elapsedRealtime());
                dispatchChronometerTick();
                postDelayed(mTickRunnable, 1000);
            } else {
                removeCallbacks(mTickRunnable);
            }
            mRunning = running;
        }
    }

你可能感兴趣的:(计时器Chronometer)