【问题标题】:How to update this textview with the Date every second如何每秒使用日期更新此文本视图
【发布时间】:2019-04-24 05:37:15
【问题描述】:
resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"

此代码有效,但我不知道您如何每秒更新resultLabel.text

如何在 Kotlin 中获取更新时间和日期,例如时钟?

【问题讨论】:

标签: android datetime kotlin


【解决方案1】:

您可以使用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
        }
    }

【讨论】:

    【解决方案2】:

    试试这个每秒更新一次文本视图

    Handler handler = new Handler();

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

    调用它开始每秒更新文本视图

    handler.postDelayed(r, 1000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多