我在我的 fragment 中使用 kotlin View 绑定(bind)。在某些情况下,应用程序崩溃并显示 IllegalStateException
且 View 为 null,我在可运行状态中访问它,该可运行状态是使用延迟 1.5 秒的处理程序调用的。
numberRunnable = Runnable {
if (mobileView.text.toString().isNotEmpty() && Utility.isMobileNumberValid(mobileView.text.toString())) {
presenter.getCustomerDetails(Utility.getServerAcceptableContactNumber(mobileView.text.toString()))
}
}
mobileView
为空
处理程序代码:
handler.postDelayed(numberRunnable, 1500)
我知道有一种可能性可以检查我的 fragment 中是否有 isAdded
,但由于我无法复制该错误,所以我不确定这是否是问题所在。
最佳答案
该操作可能在用户离开 Fragment 后运行,并且 onDestroy()
叫做。在这种状态下,Fragment 中不会有 View 实例。
一个简单的解决方法是创建一个全局变量来检查 fragment 的创建状态。将其设置为 true
在onViewCreated()
和false
在onDestroyView()
(在 super 调用之前)。然后在执行逻辑之前检查 Runnable 内的值。
更好的解决方案(尽管这会受到竞争条件的影响并且需要将每个 Runnable 分配给全局变量)可能是使用 Handler.removeCallbacks()
方法并传递所有 Runnables。
override fun onDestroyView() {
handler.removeCallbacks(numberRunnable)
}
另一种可能性是简单地说 View 可以为空:
mobileView?.let {
//Your stuff goes in here
//You can reference mobileView using "it"
}
关于android - Kotlin Android 扩展 : java. lang.IllegalStateException: View 不得为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309529/