Setting the fragment as the LifecycleOwner might cause memory leaks

1,150 阅读1分钟

Setting the fragment as the LifecycleOwner might cause memory leaks

警告内容

原文:

`

W/DataBinding: Setting the fragment as the LifecycleOwner might cause memory leaks because views lives shorter than the Fragment. Consider using Fragment's view lifecycle

`

翻译:

`

将片段设置为生命周期所有者可能会导致内存泄漏,因为视图的生存期比片段短。考虑使用 Fragment 的视图生命周期

`

原因

在程序中因为前面遇到LiveData使用postValue()后视图数据不更新,查找到解决办法是需要设置视图的lifecycleOwnerthis

原代码:


FragmentXXBinding.inflate(layoutInflater).apply {

    lifecycleOwner = this@XXFragment

}

这就是报警告的原因,直接使用了Fragment,而Fragment页面和Fragment实例生命周期是不一样的。修复也简单,按报错那样,使用viewLifecycleOwner就行:


FragmentXXBinding.inflate(layoutInflater).apply {

    lifecycleOwner = viewLifecycleOwner

}