場景:注冊賬號頁面時(shí),我們點(diǎn)擊按鈕發(fā)送驗(yàn)證碼,在等待驗(yàn)證碼時(shí),界面會有倒計(jì)時(shí)提示,這此期間按鈕不可點(diǎn)擊。當(dāng)?shù)褂?jì)時(shí)結(jié)束時(shí),按鈕恢復(fù)。
實(shí)現(xiàn)與功能都不難,這次用 RxBinding,RxJava2 的方法去實(shí)現(xiàn)。并實(shí)現(xiàn)了手動、自動停止倒計(jì)時(shí),防止多次點(diǎn)擊。

功能動態(tài)圖
要使用 RxBinding、RxJava2 先添加 Gradle 配置:
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'compile 'io.reactivex.rxjava2:rxjava:2.0.1'compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'compile 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'compile 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
首先通過 RxView.clicks() 綁定并轉(zhuǎn)換成一個(gè)倒計(jì)時(shí)的 Observable 觀察者對象。
Observable<Long> mObservableCountTime = RxView.clicks(mBtnSendMsm) //防止重復(fù)點(diǎn)擊 .throttleFirst(MAX_COUNT_TIME, TimeUnit.SECONDS) //將點(diǎn)擊事件轉(zhuǎn)換成倒計(jì)時(shí)事件 .flatMap(new Function<Object, ObservableSource<Long>>() { @Override public ObservableSource<Long> apply(Object o) throws Exception { //更新發(fā)送按鈕的狀態(tài)并初始化顯現(xiàn)倒計(jì)時(shí)文字 RxView.enabled(mBtnSendMsm).accept(false); RxTextView.text(mBtnSendMsm).accept("剩余 " + MAX_COUNT_TIME + " 秒"); //在實(shí)際操作中可以在此發(fā)送獲取網(wǎng)絡(luò)的請求 //返回 N 秒內(nèi)的倒計(jì)時(shí)觀察者對象。 return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io()).take(MAX_COUNT_TIME); } }) //將遞增數(shù)字替換成遞減的倒計(jì)時(shí)數(shù)字 .map(new Function<Long, Long>() { @Override public Long apply(Long aLong) throws Exception { return MAX_COUNT_TIME - (aLong + 1); } }) .observeOn(AndroidSchedulers.mainThread());//切換到 Android 的主線程。設(shè)置作為倒計(jì)時(shí)提示的 Consumer 被觀察者對象。
Consumer<Long> mConsumerCountTime = new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { //顯示剩余時(shí)長。當(dāng)?shù)褂?jì)時(shí)為 0 時(shí),還原 btn 按鈕. if (aLong == 0) { RxView.enabled(mBtnSendMsm).accept(true); RxTextView.text(mBtnSendMsm).accept("發(fā)送驗(yàn)證碼"); } else { RxTextView.text(mBtnSendMsm).accept("剩余 " + aLong + " 秒"); } }};訂閱點(diǎn)擊事件:
//訂閱點(diǎn)擊事件 Disposable mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);
停止倒計(jì)時(shí),但依然可以再次點(diǎn)擊。
//重置驗(yàn)證碼按鈕。RxView.clicks(mBtnClean).subscribe(new Consumer<Object>() { @Override public void accept(Object o) throws Exception { if (mDisposable != null && !mDisposable.isDisposed()) { //停止倒計(jì)時(shí) mDisposable.dispose(); //重新訂閱 mDisposable = mObservableCountTime.subscribe(mConsumerCountTime); //按鈕可點(diǎn)擊 RxView.enabled(mBtnSendMsm).accept(true); RxTextView.text(mBtnSendMsm).accept("發(fā)送驗(yàn)證碼"); } }});退出當(dāng)前頁面時(shí),銷毀清空數(shù)據(jù)。
@Overrideprotected void onDestroy() { super.onDestroy(); if (mDisposable != null) { mDisposable.dispose(); }}源碼:倒計(jì)時(shí)的各種花式實(shí)現(xiàn)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選