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透视底牌脚本(透视)切实真的是有辅助辅助(哔哩哔哩)一、wepoker透...
第9分钟绝活儿!红龙poker... 第9分钟绝活儿!红龙poker作必弊指令(透视)竟然存在有辅助工具(哔哩哔哩)一、红龙poker作必...
第3分钟办法!哈糖大菠萝破解器... 第3分钟办法!哈糖大菠萝破解器(透视)总是是有辅助教程(哔哩哔哩)1、进入到哈糖大菠萝破解器是否有挂...
四分钟步骤!wejoker辅助... 四分钟步骤!wejoker辅助软件视频(透视)确实存在有辅助神器(哔哩哔哩)进入游戏-大厅左侧-新手...
6分钟攻略!wejoker辅助... 6分钟攻略!wejoker辅助软件(透视)都是是真的有辅助透视(哔哩哔哩)wejoker辅助软件辅助...
第五分钟指南书!hhpoker... 第五分钟指南书!hhpoker免费透视脚本(透视)其实是真的有辅助教程(哔哩哔哩)1)hhpoker...
第九分钟绝活!wepoker有... 第九分钟绝活!wepoker有没有机器人(透视)一贯是有辅助教程(哔哩哔哩)1、wepoker有没有...
第9分钟讲义!wepoker透... 第9分钟讲义!wepoker透视底牌脚本(透视)总是真的是有辅助透视(哔哩哔哩)1、许多玩家不知道w...
四分钟大纲!epoker免费透... 四分钟大纲!epoker免费透视脚本(透视)竟然是真的有辅助下载(哔哩哔哩)1、任何epoker免费...
第二分钟指南!wepoker免... 第二分钟指南!wepoker免费透视脚本(透视)都是是有辅助透视(哔哩哔哩)1、许多玩家不知道wep...