我的片段如下:
open lateinit var recyclerView: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater.cloneInContext(contextThemeWrapper).inflate(R.layout.xxx, container, false)
if (savedInstanceState == null) {
recyclerView = rootView.findViewById(R.id.sss)
}
}
我在日志中看到此错误:
Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{tv.lattelecom.app/tv.lattelecom.app.main.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property recyclerView has not been initialized
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4720)
我很好奇,这是怎么发生的以及为什么发生?另外,也不知道如何重现此错误。我猜这是在应用程序已经在后台运行了一段时间并且已经轮换的时候发生的。想法?
答案 0 :(得分:4)
您可能想检查recyclerView
是否已用if(savedInstanceState == null)
初始化,最好使用if(recyclerView::lateinitVar.isInitialized)
。
请参见http://kotlinlang.org/docs/reference/whatsnew12.html#checking-whether-a-lateinit-var-is-initialized