偷懶寫作坛增,只貼代碼游沿!
val timer:TextView = findViewById(R.id.textView) //這里的 timer 就是你要控制顯示倒計(jì)時(shí)效果的 TextView
val mSubscription: Subscription? = null // Subscription 對(duì)象,用于取消訂閱關(guān)系蔫慧,防止內(nèi)存泄露
//開始倒計(jì)時(shí)蟀架,用 RxJava2 實(shí)現(xiàn)
private fun timer() {
val count = 59L
Flowable.interval(0, 1, TimeUnit.SECONDS)//設(shè)置0延遲,每隔一秒發(fā)送一條數(shù)據(jù)
.onBackpressureBuffer()//加上背壓策略
.take(count) //設(shè)置循環(huán)次數(shù)
.map{ aLong ->
count - aLong //
}
.observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI線程
.subscribe(object : Subscriber<Long> {
override fun onSubscribe(s: Subscription?) {
timer.isEnabled = false//在發(fā)送數(shù)據(jù)的時(shí)候設(shè)置為不能點(diǎn)擊
timer.textColor = resources.getColor(Color.GRAY)//背景色設(shè)為灰色
mSubscription = s
s?.request(Long.MAX_VALUE)//設(shè)置請(qǐng)求事件的數(shù)量兑障,重要,必須調(diào)用
}
override fun onNext(aLong: Long?) {
timer.text = "${aLong}s后重發(fā)" //接受到一條就是會(huì)操作一次UI
}
override fun onComplete() {
timer.text = "點(diǎn)擊重發(fā)"
timer.isEnabled = true
timer.textColor = Color.WHITE
mSubscription?.cancel()//取消訂閱蕉汪,防止內(nèi)存泄漏
}
override fun onError(t: Throwable?) {
t?.printStackTrace()
}
})
}