我有一个 Android 应用程序,有一个 Fragment Activity 和一个 ID 为“debugLog”的 TextView。 我想每 500 毫秒用新数据更新一次 Textview。
我的问题是,Timer() 只工作一次,然后永远不会执行?
class DiagnoseUart : Fragment() {
// TODO: Rename and change types of parameterss
val logWriter = LogWriter();
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_diagnose_uart, container, false);
val handler = Handler()
val debugLog = view.findViewById<TextView>(R.id.debugLog);
debugLog.movementMethod = ScrollingMovementMethod();
Timer().schedule(timerTask {
val log = logWriter.getLog();
[email protected]()?.runOnUiThread(Runnable {
debugLog.text = log;
})
}, 500);
return view;
}
}
希望对您有所帮助。 当然还有更多的解决方案。
var count = 1
Timer().schedule(time = Date(), period = 500, action = {
binding.textHome.text = count.toString()
count += 1
})
或
var count = 1
val timerHandler = Handler()
val timerRunnable: Runnable = object : Runnable {
override fun run() {
binding.textHome.text = String.format("%d", count)
count+=1
timerHandler.postDelayed(this, 500)
}
}
timerRunnable.run()
或
var count = 1
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
//Call your function here
binding.textHome.text = count.toString()
count += 1
handler.postDelayed(this, 500)//1 sec delay
}
}, 0)
谢谢你,
此代码适用于 API 23:
var count = 1
Timer().schedule(time = Date(), period = 500, action = {
binding.textHome.text = count.toString()
count += 1
})
还有这个:
val timerRunnable: Runnable = object : Runnable {
override fun run() {
val log = logWriter.getLog();
[email protected]()?.runOnUiThread(Runnable {
debugLog.text = log;
})
handler.postDelayed(this, 500);
}
}
timerRunnable.run();
当我的片段视图关闭时,计时器会自动销毁吗?