欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Kotlin和Handler实现倒计时

程序员文章站 2022-07-14 17:15:16
...

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)
    }
}