VerificationCountDownTimer
3409 ワード
認証コードを取得するときによく使われるコントロールは、ボタンをクリックすると60秒のカウントダウンが表示されます.実はこの原理は簡単で、textviewとTimerの混合使用です.
ダイレクトコード
メッセージ処理をよく見て
ダイレクトコード
public class VerificationCountDownTimer extends CountDownTimer {
private final String text;
private final TextView view;
private final static long MILLIS_IN_FUTURE=60000;// 60
private final static long COUNT_DOWN_INTERVAL=1000;//1
/** * @param millisInFuture The number of millis in the future from the call * to {@link #start()} until the countdown is done and {@link #onFinish()} * is called. * @param countDownInterval The interval along the way to receive * {@link #onTick(long)} callbacks. */
public VerificationCountDownTimer(long millisInFuture, long countDownInterval , TextView textView) {// super(countDownInterval, millisInFuture); super(MILLIS_IN_FUTURE, COUNT_DOWN_INTERVAL);
this.view = textView;
text = textView.getText().toString();
}
@Override
public void onFinish() {//
view.setText(text);
view.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished) {
view.setClickable(false);//
view.setText(millisUntilFinished / COUNT_DOWN_INTERVAL + " ");
}
}
使用時のみ verificationCountDown = (TextView)findViewById(R.id.verificationCountDown);
verificationCountDown.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { //0,0
new VerificationCountDownTimer(0,0,verificationCountDown);
}
});
簡単ではないでしょうか.では、CountDownTimerソースコードを見てみましょう.public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
// SystemClock.elapsedRealtime()
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
//
return this;
}メッセージ処理をよく見て
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
//
if (mCancelled) {
return;
}
//
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
// 0 , finish
if (millisLeft <= 0) {
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft); // take into account user's onTick taking time to execute long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to // complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};