Android Chronometer类

来源:互联网 发布:跳蚤街二手市场软件 编辑:程序博客网 时间:2024/06/11 08:34

Android Chronometer类

Chronometer类是一个简单的计时器。

1、简单用法

android:format设置文字格式,默认是MM:SS"或"H:MM:SS"。以%s来格式化。
<Chronometerandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:format="计时:%s"/>

2、Chronometer的方法

start开始计时,stop停止计时。
public void start() {mStarted = true;updateRunning();}public void stop() {mStarted = false;updateRunning();}
start和stop都会调用updateRunning方法,只是mStarted的状态不一样。
updateRunning方法,当running为true时,会修改文字,否则将暂停计时。

private void updateRunning() {boolean running = mVisible && mStarted;if (running != mRunning) {if (running) {updateText(SystemClock.elapsedRealtime());dispatchChronometerTick();postDelayed(mTickRunnable, 1000);} else {removeCallbacks(mTickRunnable);}mRunning = running;}}
updateText方法,把现在的时间和mBase相比较,得到计时时间,并格式化显示。而mBase是在Chronometer初始化时设置。
private synchronized void updateText(long now) {mNow = now;long seconds = mCountDown ? mBase - now : now - mBase;seconds /= 1000;boolean negative = false;if (seconds < 0) {seconds = -seconds;negative = true;}String text = DateUtils.formatElapsedTime(mRecycle, seconds);if (negative) {text = getResources().getString(R.string.negative_duration, text);}if (mFormat != null) {Locale loc = Locale.getDefault();if (mFormatter == null || !loc.equals(mFormatterLocale)) {mFormatterLocale = loc;mFormatter = new Formatter(mFormatBuilder, loc);}mFormatBuilder.setLength(0);mFormatterArgs[0] = text;try {mFormatter.format(mFormat, mFormatterArgs);text = mFormatBuilder.toString();} catch (IllegalFormatException ex) {if (!mLogged) {Log.w(TAG, "Illegal format string: " + mFormat);mLogged = true;}}}setText(text);}
setFormat设置文字格式。
setBase设置起始时间。

public void setBase(long base) {mBase = base;dispatchChronometerTick();updateText(SystemClock.elapsedRealtime());}
setOnChronometerTickListener设置监听器。
setCountDown方法设置是否是倒计时,只有版本大于24才有效。