1. Chronometer类
Chronometer
是一个简单的计时器。
主要配置
format
,显示格式,默认是"MM:SS"或"H:MM:SS",以%s来格式化。countDown
,是否倒计时,与base
时间相比较
主要方法
start()
,开始计时stop()
,停止计时setBase(long)
,设置计时基准时间setFormat(String)
,设置显示格式setCountDown(boolean)
,设置是否是倒计时,只有版本大于24才有效setOnChronometerTickListener(OnChronometerTickListener)
,设置监听器
实例代码
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.setFormat("计时开始 %s");
mChronometer.start();
效果如下
2. Chronometer代码分析
start()
和stop()
方法修改了mStarted
的状态,然后调用updateRunning()
。
Chronometer
状态由三部分组成,mVisible
(Window是否可见)、mStarted
(Chronometer
开始计时)和isShown
(View
是否可见)。如果状态变化,修改当前控件。updateText(long)
修改界面,dispatchChronometerTick()
触发监听事件。postDelayed(Runnable, long)
在一秒后修改界面。
public void start() {
mStarted = true;
updateRunning();
}
public void stop() {
mStarted = false;
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;
}
}
private final Runnable mTickRunnable = new Runnable() {
@Override
public void run() {
if (mRunning) {
updateText(SystemClock.elapsedRealtime());
dispatchChronometerTick();
postDelayed(mTickRunnable, 1000);
}
}
};
updateText(long)
修改当前界面,首先拿当前时间和mBase
时间作比较,second
是两种之间的差值。DateUtils
把second
格式化,一般是"MM:SS"或"H:MM:SS",输出text
。如果定义了format格式,利用Formatter
将text
进一步格式化。
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);
}
dispatchChronometerTick()
触发监听事件。
void dispatchChronometerTick() {
if (mOnChronometerTickListener != null) {
mOnChronometerTickListener.onChronometerTick(this);
}
}
setFormat(String)
设置显示格式
public void setFormat(String format) {
mFormat = format;
if (format != null && mFormatBuilder == null) {
mFormatBuilder = new StringBuilder(format.length() * 2);
}
}
setBase(long)
设置计时基准时间
public void setBase(long base) {
mBase = base;
dispatchChronometerTick();
updateText(SystemClock.elapsedRealtime());
}
相关文章
Android Picker控件
Android Clock控件
Android Chronometer控件
Android Handler类
Java Formatter类