我已将代码切换到 View Binding,但现在在线程中更新 UI 时遇到问题。该代码在合成语法中运行良好。我收到错误:
java.lang.NullPointerException
at HomeFragment.getBind(HomeFragment.kt:25)
at HomeFragment.updateHomeUI$lambda-6(HomeFragment.kt:190)
at HomeFragment.$r8$lambda$7K03ZbIZrY_5ngvcMBPsw15TPbw(Unknown Source:0)
at HomeFragment$$ExternalSyntheticLambda10.run(Unknown Source:2)
at java.lang.Thread.run(Thread.java:919)
我的代码:
class HomeFragment : Fragment(R.layout.fragment_home) {
private var _binding: FragmentHomeBinding? = null
private val bind get() = _binding!! // <-- line 25
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return bind.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
updateHomeUI()
}
private fun updateHomeUI() {
Thread {
while (bind.tvName != null) { // Stop the loop after changing the fragment
...
// Lots of UI update like this:
if (activity != null) (activity as MainActivity).runOnUiThread { bind.tvName?.text = str }
...
Thread.sleep(1000)
}
}.start()
}
当我切换到不同的片段时出现错误。如果我是对的,线程在 onDestroyView () 之后运行并且绑定为空。我想出了暂停 onDestroyView 直到 Thread 完成的想法,但我认为这不是最好的解决方案,因为它可能会停止整个应用程序。
override fun onDestroyView() {
super.onDestroyView()
threadStop = true
while (threadRunning) {
Thread.sleep(1)
}
_binding = null
}
private fun updateHomeUI() {
Thread {
threadRunning = true
threadStop = false
while (!threadStop) {
...
}
threadRunning = false
}
}
如何正确避免这个问题?
此致!