【发布时间】:2019-04-24 05:37:15
【问题描述】:
resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"
此代码有效,但我不知道您如何每秒更新resultLabel.text。
如何在 Kotlin 中获取更新时间和日期,例如时钟?
【问题讨论】:
resultLabel.text = "${SimpleDateFormat("MM/dd hh:mm").format(Date())}"
此代码有效,但我不知道您如何每秒更新resultLabel.text。
如何在 Kotlin 中获取更新时间和日期,例如时钟?
【问题讨论】:
您可以使用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
}
}
【讨论】:
试试这个每秒更新一次文本视图
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);
【讨论】: