需求:
登陸或者註冊時點擊獲取驗證碼按鈕,進行60s倒計時,倒計時過程中不允許點擊按鈕。倒計時秒數需要實時顯示
效果圖:
圖1是未獲取之前,圖2是點擊之後
思路:
倒計時一般有幾種解決方案,常用用Timer,Handler,RxJava。
不過經過測試Timer和Handler時間都有誤差,不準。項目建議採用RxJava
關鍵代碼:
在項目的build.gradle中添加RxJava2依賴
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.7'
注:如果項目已經有RxJava2就不用重複添加了
TimeUtils
public static Disposable dealCountDownS(long second, Consumer<Long> nextObserver, Consumer<Throwable> errorObserver, Action completeObserver ) {
return Observable
.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.take(second)
.subscribe(nextObserver,errorObserver,completeObserver);
}
開始使用:
public class RegOneNewActivity extends BaseActivity<RegOneIView, RegOnePresenter> implements RegOneIView {
@BindView(R.id.tv_get_code)
TextView tvGetCode;
//是否開啓倒計時
private boolean isStartCountDown;
private Disposable subscription;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHeadView(R.layout.activity_regist_one_new, false);
showRealView();
}
@Override
protected void initPrClick() {
super.initPrClick();
//獲取驗證碼
ViewShow.prClick(tvGetCode, new Action1() {
@Override
public void call(Object o) {
if (!isStartCountDown) {
onGetRegCode()
}
}
});
}
public void onGetRegCode() {
//獲取驗證碼成功,進行倒計時
isStartCountDown = true;
//Constant.CODE_COUNTDOWN_TIME :60
tvGetCode.setText(Constant.CODE_COUNTDOWN_TIME + "s");
subscription = TimeUtils.dealCountDownS(Constant.CODE_COUNTDOWN_TIME, new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
//每隔一秒
if (null != tvGetCode) {
tvGetCode.setText((TextUtils.concat(String.valueOf(Math.abs(aLong - Constant.CODE_COUNTDOWN_TIME)), "s")).toString());
}
}
}, new Consumer<Throwable>() {
//倒計時錯誤的回調
@Override
public void accept(Throwable throwable) throws Exception {
if (null != tvGetCode) {
tvGetCode.setText(mContext.getString(R.string.get_code));
}
isStartCountDown = false;
}
}, new Action() {
//倒計時完成的回調
@Override
public void run() throws Exception {
if (null != tvGetCode) {
tvGetCode.setText(R.string.get_code);
}
isStartCountDown = false;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}