如何使用Date每秒更新此textview

问题描述 投票:-2回答:2
resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"

这段代码正在运行,但我不知道如何每秒更新resultLabel.text

我如何在Kotlin获得像时钟一样的更新时间和日期?

android datetime kotlin
2个回答
2
投票

你可以使用Timer类更新你的价值。

val timer = Timer()
        timer?.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                updateTimer()
            }
        }, 0, 1000)


private fun updateTimer() {
        runOnUiThread {
            resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"
        }
    }

这是停止时间的方法。

private fun stopTimer() {
        if (timer != null) {
            timer?.cancel()
            timer?.purge()
            timer = null
        }
    }

0
投票

尝试这样每秒更新textview

Handler trades = new handler();

final Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");
        resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"
    }
};

调用此方法每秒开始更新textview

handler.postDelayed(r, 1000);
© www.soinside.com 2019 - 2024. All rights reserved.