一、效果图
文章来源:https://www.toymoban.com/news/detail-827441.html
二、ExtendContext.kt 文件代码
注意:创建ExtendContext.kt选择file
使用kotlin扩展方法的特性创建countDown扩展方法,避免多个地方使用倒计时重复创建countDown方法
文章来源地址https://www.toymoban.com/news/detail-827441.html
package com.example.baselib.extension
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
fun FragmentActivity.countDown(
timeMillis: Long = 1000,//默认时间间隔 1 秒
time: Int = 3,//默认时间为 3 秒
start: (scop: CoroutineScope) -> Unit,
end: () -> Unit,
next: (time: Int) -> Unit,
error: (msg: String?) -> Unit
) {
lifecycleScope.launch {
flow {
(time downTo 1).forEach {
delay(timeMillis)
emit(it)
}
}.onStart {
start(this@launch)
}.onCompletion {
end()
}.catch {
error(it.message ?: "countDown 出现未知错误")
}.collect {
next(it)
}
}
}
三、MainActivity.kt代码
package com.example.testkotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.baselib.extension.countDown
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
class MainActivity : AppCompatActivity() {
private var mCountDown: CoroutineScope? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
}
private fun loadData() {
this.countDown(time = 5, start = {
mCountDown = it
}, end = {
Log.i("==", "倒计时结束了")
}, next = {
Log.i("==", "剩余 $it 秒")
}, error = {
})
}
override fun onDestroy() {
mCountDown?.let {
it.cancel()
}
super.onDestroy()
}
}
四、build.gradle.kts代码
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.example.testkotlin"
compileSdk = 34
defaultConfig {
applicationId = "com.example.testkotlin"
minSdk = 23
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
到了这里,关于Kotlin:使用flow实现倒计时功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!