为什么片段中`by lazy` 委托的这种奇怪行为

Jib*_*bbo 5 android android-lifecycle android-fragments kotlin

前几天,我贴这个当您在屏幕多次相同的布局有关使用综合性能的问题。

答案很棒,但是在我尝试了几天之后,我注意到了一个奇怪的行为:

当从片段(包含对惰性委托获得的视图的引用的片段)前进然后返回(我使用transaction.commit()andmanager.popBackStack()来执行此操作)时,标签将为空。我已经用调试器检查过那里是否有任何内容为空,但什么都没有。

这似乎是工作的唯一解决办法是更换by lazylateinit var和分配他们onViewCreated

你知道为什么吗?我使用的解决方案仍然“好”作为 kotlin 习语吗?

为了完整起见,我包含了两段代码:

部分工作之一:

private val foundTitle by lazy { detailContainer1.title }
private val foundDescription by lazy { detailContainer1.description }

private val wantedTitle by lazy { detailContainer2.title }
private val wantedDescription by lazy { detailContainer2.description }
Run Code Online (Sandbox Code Playgroud)

总是工作一个:

 private lateinit var foundTitle: TextView
 private lateinit var foundDescription: TextView

 private lateinit var wantedTitle: TextView
 private lateinit var wantedDescription: TextView

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

   foundTitle = detailContainer1.title
   foundDescription = detailContainer1.description

   wantedTitle = detailContainer2.title
   wantedDescription = detailContainer2.description

 }
Run Code Online (Sandbox Code Playgroud)

提前致谢

Paw*_*wel 5

Fragment 的视图在被移除时会被破坏 - 但lazy字段不会清除它们的引用,因此它们本质上是在泄漏先前的视图。

如果可能,您的项目中应该始终具有唯一的视图 ID,即使它们不在同一布局中 - 重复可能会导致多个问题(就像您的一样)。

如果您能够直接使用kotlin 扩展,它会在片段视图被自动销毁时生成用于查找、缓存和清除视图缓存的代码。

尝试从片段缓存中“获取”视图,而不是将它们分配给字段:

private val foundTitle 
    get() = detailContainer1.title
private val foundDescription
    get() = detailContainer1.description

private val wantedTitle
    get() = detailContainer2.title
private val wantedDescription
    get() = detailContainer2.description
Run Code Online (Sandbox Code Playgroud)