dum*_*azy 6 android android-fragments kotlin kotlin-lateinit
在我的Activity中,我有一个lateinit
名为controller
Fragment使用的属性.此属性已初始化Activity.onCreate()
.我Fragment
得到它的参考回到我Activity
通过onAttach()
.在Fragment
随后调用myActivity.controller
在Fragment.onCreate()
.
通常controller
首先在其中初始化Activity.onCreate()
,然后Fragment
添加.所以这很好用.
但是当我Activity
被杀死时,它会试图重建自己及其碎片.这导致在初始化发生之前Fragment.onCreate()
被调用.Activity.onCreate()
这些是我现在看到的选项:
controller
之前初始化super.onCreate()
(如果可能的话)myActivity.controller
到以后的生命周期回调,如onViewCreated()
::controller.isInitialized
Kotlin 1.2中提供的东西这是我最好的选择?
通过回顾Fragment
生命周期,事实上最安全的做法就是#onActivityCreated(android.os.Bundle)
.
即使#onAttach()
看起来它被Fragment
附加到它时被调用Activity
,我也不确定这是否完全有保证,因为旧#onAttach(android.app.Activity)
的已被弃用,并且#onAttach(android.content.Context)
建议使用新的.