应该在自定义视图中调用 findViewTreeLifecycleOwner() 的位置?

Ben*_*det 10 android android-fragments android-jetpack

view.findViewTreeLifecycleOwner()Fragment 1.3.0引入了获取视图生命周期Owner的方法。在片段中,此方法返回nullbefore onViewCreated()

我需要使用协程在自定义视图中进行一些初始化,因此我需要调用findViewTreeLifecycleOwner().lifecycleScope以获取协程作用域。在视图中调用它的最佳位置是什么?

起初我尝试在构造函数中调用它,因为它是为初始化而创建的,但它是在片段之前调用的,onViewCreated()因此该方法返回 null。所以我尝试将它放入其中onAttachedToWindow()并且它可以工作,但我真的不知道在这里进行初始化是否是一个好主意。

class TestView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {

    init {
        // return null here as constructor is called before fragment's onViewCreated()
        findViewTreeLifecycleOwner()!!.lifecycleScope.launchWhenStarted { 
            ...
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // here it works because it's called after  fragment's onViewCreated()
        findViewTreeLifecycleOwner()!!.lifecycleScope.launchWhenStarted {
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)