Android Kotlin:在我的按钮内部的倒计时计时器。
创始人
2024-08-14 16:00:29
0

这是一个在Android Kotlin中,在按钮内部实现倒计时计时器的示例代码:

首先,在你的布局文件中添加一个按钮和一个TextView,用于显示倒计时时间:

然后,在你的Activity或Fragment中,找到按钮和TextView,并实现倒计时逻辑:

class MainActivity : AppCompatActivity() {

    private lateinit var startButton: Button
    private lateinit var countdownTextView: TextView

    private lateinit var countDownTimer: CountDownTimer

    private var timeLeftInMillis: Long = 60000 // 倒计时总时长为1分钟
    private val countDownInterval: Long = 1000 // 每秒更新一次

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 找到按钮和TextView
        startButton = findViewById(R.id.startButton)
        countdownTextView = findViewById(R.id.countdownTextView)

        // 设置按钮的点击事件
        startButton.setOnClickListener {
            startCountdown()
        }
    }

    private fun startCountdown() {
        countDownTimer = object : CountDownTimer(timeLeftInMillis, countDownInterval) {
            override fun onTick(millisUntilFinished: Long) {
                timeLeftInMillis = millisUntilFinished
                updateCountdownText()
            }

            override fun onFinish() {
                // 倒计时结束时的逻辑
                countdownTextView.text = "倒计时结束"
            }
        }

        countDownTimer.start()
    }

    private fun updateCountdownText() {
        val minutes = (timeLeftInMillis / 1000) / 60
        val seconds = (timeLeftInMillis / 1000) % 60

        val timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)
        countdownTextView.text = timeLeftFormatted
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer.cancel() // 在Activity或Fragment销毁时取消计时器
    }
}

通过以上代码,当你点击按钮后,将会启动一个倒计时计时器,每秒更新一次TextView中的倒计时时间,直到倒计时结束。

相关内容

热门资讯

科普透视!wepoker作弊方... 科普透视!wepoker作弊方法,微信小程序微乐房间有技巧吗,绝活教程(了解有挂)-哔哩哔哩1、不需...
关于透视!拱趴大菠萝十三水作弊... 关于透视!拱趴大菠萝十三水作弊,微乐自建房辅助多少钱一个月,机巧教程(了解有挂)-哔哩哔哩1、首先打...
详情透视!wepoker怎么拿... 详情透视!wepoker怎么拿到好牌,微乐广西麻辣,练习教程(有挂方针)-哔哩哔哩1、wepoker...
揭露透视!哈糖大菠萝破解器,微... 揭露透视!哈糖大菠萝破解器,微信卡五星小程序辅助,攻略教程(今日头条)-哔哩哔哩哈糖大菠萝破解器脚本...
辅助透视!德普之星透视软件免费... 辅助透视!德普之星透视软件免费入口官网,微乐河南小程序辅助器免费,讲义教程(新版有挂)-哔哩哔哩1、...
曝光透视!uupoker透视,... 曝光透视!uupoker透视,微信小程序微乐辅助器教程,操作教程(有挂方式)-哔哩哔哩1、不需要AI...
解迷透视!pokemmo手机脚... 解迷透视!pokemmo手机脚本,微乐自建房免费黑科技下载,妙招教程(真的有挂)-哔哩哔哩1、pok...
解迷透视!德州透视竞技联盟,微... 解迷透视!德州透视竞技联盟,微信小程序 微乐陕西挖坑 外挂,要领教程(有挂方法)-哔哩哔哩1、德州透...
解谜透视!wepoker辅助器... 解谜透视!wepoker辅助器下载,广西微乐小程序辅助器,技法教程(有挂教程)-哔哩哔哩1、wepo...
详情透视!哈糖大菠萝攻略,微乐... 详情透视!哈糖大菠萝攻略,微乐自建房怎么提高运气,机巧教程(有挂分享)-哔哩哔哩1、点击下载安装,哈...