android 短視訊開發,依靠Kotlin和Handler實現倒計時
阿新 • • 發佈:2022-04-15
android 短視訊開發,依靠Kotlin和Handler實現倒計時效果
1、佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".countDown.CountDownActivity">
<TextView
android:id="@+id/tvCountDown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="剩餘60秒"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="24dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
2、Activity當中邏輯處理
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.example.myapplication.R
import kotlinx.android.synthetic.main.activity_count_down.*
class CountDownActivity : AppCompatActivity() {
private val handler = Handler()
private var mCountNum = 60
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_count_down)
tvCountDown.setOnClickListener {
handler.postDelayed(countDown, 0)
}
}
private val countDown = object : Runnable {
override fun run() {
tvCountDown.text = "剩餘" + mCountNum + "秒"
tvCountDown.isEnabled = false
if (mCountNum > 0) {
handler.postDelayed(this, 1000)
} else {
tvCountDown.text = "重新倒計時"
tvCountDown.isEnabled = true
mCountNum = 60
}
mCountNum--
}
}
private fun removeCountDOwn() {
handler.removeCallbacks(countDown)
}
}
以上就是 android 短視訊開發,依靠Kotlin和Handler實現倒計時效果,更多內容歡迎關注之後的文章