本文介紹了Android使用Kotlin和RxJava 2.×實現短信驗證碼倒計時效果,分享給大家,具體如下:
場景:注冊賬號頁面時,我們點擊按鈕發送驗證碼,在等待驗證碼時,界面會有倒計時提示,這此期間按鈕不可點擊。當倒計時結束時,按鈕恢復。
實現代碼
val timer:TextView = findViewById(R.id.textView) //這里的 timer 就是你要控制顯示倒計時效果的 TextView
val mSubscription: Subscription? = null // Subscription 對象,用于取消訂閱關系,防止內存泄露
//開始倒計時,用 RxJava2 實現
private fun timer() {
val count = 59L
Flowable.interval(0, 1, TimeUnit.SECONDS)//設置0延遲,每隔一秒發送一條數據
.onBackpressureBuffer()//加上背壓策略
.take(count) //設置循環次數
.map{ aLong ->
count - aLong //
}
.observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI線程
.subscribe(object : Subscriber<Long> {
override fun onSubscribe(s: Subscription?) {
timer.isEnabled = false//在發送數據的時候設置為不能點擊
timer.textColor = resources.getColor(Color.GRAY)//背景色設為灰色
mSubscription = s
s?.request(Long.MAX_VALUE)//設置請求事件的數量,重要,必須調用
}
override fun onNext(aLong: Long?) {
timer.text = "${aLong}s后重發" //接受到一條就是會操作一次UI
}
override fun onComplete() {
timer.text = "點擊重發"
timer.isEnabled = true
timer.textColor = Color.WHITE
mSubscription?.cancel()//取消訂閱,防止內存泄漏
}
override fun onError(t: Throwable?) {
t?.printStackTrace()
}
})
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。