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

相关内容

热门资讯

透视挂!竞技联盟破解版最新版(... 透视挂!竞技联盟破解版最新版(透视)开挂辅助挂(确实是真的挂)-哔哩哔哩1、实时竞技联盟破解版最新版...
透视ai代打!wepoker插... 透视ai代打!wepoker插件辅助,购买的wpk辅助在哪里下载,诀窍教程(原来真的有挂)-哔哩哔哩...
透视线上!hhpoker软件安... 透视线上!hhpoker软件安装包(透视)开挂辅助器(本来存在有挂)-哔哩哔哩1、完成hhpoker...
透视新版!wepoker怎么破... 透视新版!wepoker怎么破解游戏,uupoker有透视吗,大纲教程(切实是有挂)-哔哩哔哩1、全...
透视app!来玩德州破解器,w... 透视app!来玩德州破解器,wepoker辅助器软件下载,方针教程(真是有挂)-哔哩哔哩1)wepo...
透视辅助!wejoker辅助脚... 透视辅助!wejoker辅助脚本(透视)开挂辅助工具(果然真的是有挂)-哔哩哔哩1、wejoker辅...
透视app!hhpoker辅助... 透视app!hhpoker辅助实战视频,wepoker透视功能下载,法子教程(切实有挂)-哔哩哔哩一...
透视输赢!约局吧是否有挂(透视... 透视输赢!约局吧是否有挂(透视)开挂辅助软件(其实是有挂)-哔哩哔哩约局吧是否有挂辅助器中分为三种模...
透视代打!来玩德州破解器,we... 透视代打!来玩德州破解器,we-poker辅助器,手册教程(总是真的有挂)-哔哩哔哩1、来玩德州破解...
透视辅助挂!拱趴大菠萝万能辅助... 透视辅助挂!拱趴大菠萝万能辅助器(透视)开挂辅助脚本(一贯是真的挂)-哔哩哔哩1、拱趴大菠萝万能辅助...