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免费透视(透视)新2025教程(有挂教程);亲,...
透视辅助!wepoker私人局... 透视辅助!wepoker私人局规律,wpk辅助,可靠教程(有挂秘笈);运wepoker私人局规律辅助...
透视安装!wepoker分析,... 透视安装!wepoker分析,wepoker有辅助功能吗(透视)分享教程(有挂解密);一、wepok...
透视透视!wepoker到底有... 透视透视!wepoker到底有没有透视,德扑圈透视,细节揭秘(有挂教程);1、完成wepoker到底...
透视教学!智星德州插件2024... 透视教学!智星德州插件2024最新版,pokemmo脚本辅助下载,曝光教程(有挂攻略)1、智星德州插...
透视计算!wepokerplu... 透视计算!wepokerplus作弊,黑侠破解wepoker(透视)必胜教程(有挂教程)1、黑侠破解...
透视了解!cloudpoker... 透视了解!cloudpoker怎么开挂,wepokerplus脚本,解密教程(有挂教程)1、操作简单...
透视了解!wepoker到底有... 透视了解!wepoker到底有没有透视,wepoker怎么增加运气(透视)透视教程(有挂解说)1)w...
透视科技!约局吧如何查看是否有... 透视科技!约局吧如何查看是否有挂,wepoker有辅助插件吗,细节揭秘(有挂秘籍);1、约局吧如何查...
透视中牌率!we-poker软... 透视中牌率!we-poker软件,wepoker脚本下载(透视)微扑克教程(有挂规律)1、下载好we...