![](/img/trans.png)
[英]java.lang.IllegalStateException: TextView must not be null (Android/Kotlin)
[英]Kotlin Android Extensions : java.lang.IllegalStateException: view must not be null
我在片段中使用Kotlin视图绑定。 在某些情况下,应用程序崩溃且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
为null
处理程序代码: handler.postDelayed(numberRunnable, 1500)
我知道有一种可能性可以检查片段中是否isAdded
我的isAdded
,但是由于我无法复制该错误,因此不确定是否是问题所在。
您不能假设1.5秒后视图仍附加到视图层次结构。
在片段不再活动时,将numberRunnable
handler.removeCallbacks(numberRunnable)
添加到onStop()
生命周期回调中,以删除numberRunnable
。
还要问自己一个问题,为什么需要延误。
用户离开Fragment并调用onDestroy()
后,该操作可能会运行。 在这种状态下,片段中将没有View实例。
一个简单的解决方法是创建一个全局var来检查Fragment的创建状态。 在超级调用之前,在onViewCreated()
其设置为true
,在onDestroyView()
onViewCreated()
其设置为false
。 然后在执行逻辑之前检查Runnable内部的值。
更好的解决方案(尽管这受竞争条件的影响,并且需要将每个Runnable分配给全局变量)可能是使用Handler.removeCallbacks()
方法并传递所有Runnable。
override fun onDestroyView() {
handler.removeCallbacks(numberRunnable)
}
还有另一种可能性是简单地说View是可为空的:
mobileView?.let {
//Your stuff goes in here
//You can reference mobileView using "it"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.