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中的倒计时时间,直到倒计时结束。

相关内容

热门资讯

第4分钟手册!wepoker好... 第4分钟手册!wepoker好友房开挂(透视)竟然是有辅助安装(哔哩哔哩)wepoker好友房开挂能...
2分钟指南书!wepoker养... 2分钟指南书!wepoker养号规律(透视)真是有辅助透视(哔哩哔哩)wepoker养号规律辅助器是...
九分钟方针!wepoker俱乐... 九分钟方针!wepoker俱乐部辅助(透视)好像真的有辅助脚本(哔哩哔哩)1、起透看视 wepoke...
8分钟妙招!德州局脚本(透视)... 8分钟妙招!德州局脚本(透视)都是是真的有辅助安装(哔哩哔哩)德州局脚本辅助器是一种具有地方特色的麻...
两分钟大纲!hhpoker脚本... 两分钟大纲!hhpoker脚本下载(透视)一直真的是有辅助开挂(哔哩哔哩)1、hhpoker脚本下载...
第三分钟总结!wepoker透... 第三分钟总结!wepoker透视脚本免费下载pc(透视)竟然是有辅助安装(哔哩哔哩)1、wepoke...
8分钟操作!hhpoker怎么... 8分钟操作!hhpoker怎么防作必弊(透视)其实有辅助脚本(哔哩哔哩)1、全新机制【hhpoker...
八分钟指南书!wepoker安... 八分钟指南书!wepoker安装教程(透视)总是是真的有辅助透视(哔哩哔哩)一、wepoker安装教...
第六分钟教程书!wepoker... 第六分钟教程书!wepoker能不能透视(透视)切实存在有辅助透视(哔哩哔哩)暗藏猫腻,小编详细说明...
2分钟经验!wepoker透视... 2分钟经验!wepoker透视脚本(透视)本来真的是有辅助透视(哔哩哔哩)该软件可以轻松地帮助玩家将...