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

相关内容

热门资讯

透视黑科技"wepo... 透视黑科技"wepoker私人局规律"详细辅助安装教程(原来有挂)关于wepoker私人局规律机制的...
总算了解!wepoker免费钻... 《总算了解!wepoker免费钻石,约局吧是否有挂,我来教教你(有挂神器)》 约局吧是否有挂软件透明...
透视安卓版"wepo... 透视安卓版"wepoker代打辅助机器人"详细辅助力荐教程(一直有挂);亲真的是有正版授权,小编(透...
免费测试版!hhpoker透视... 1、免费测试版!hhpoker透视方法,wepoker可以免费玩吗,AI教程(有挂方法);详细教程。...
透视安卓版"hhpo... 透视安卓版"hhpoker辅助挂下载"详细辅助黑科技教程(从来真的有挂);支持多人共享记分板与复盘,...
玩家必用!hhpoker透视脚... 1、玩家必用!hhpoker透视脚本,wepoker私人局俱乐部辅助,总结教程(有挂教程)(UU p...
透视中牌率"哈糖大菠... 透视中牌率"哈糖大菠萝挂"详细辅助黑科技教程(果然真的有挂);建议优先通过哈糖大菠萝挂透明挂内置帮助...
实测发现!wepoker轻量版... 实测发现!wepoker轻量版辅助,wepoker公共底牌,2025版教程(有挂教程);大神普及一款...
透视数据"hhpok... 透视数据"hhpoker到底可以作弊码"详细辅助透视教程(本然是真的有挂);支持多人共享记分板与复盘...
实测交流!aapoker透视脚... 您好,wepoker破解是真的还是假的这款游戏可以开挂的,确实是有挂的,需要了解加微【1367043...