【问题标题】:Android repeatOnLifecycle in fragment inside ViewPager2ViewPager2中片段中的Android repeatOnLifecycle
【发布时间】:2021-12-12 13:02:15
【问题描述】:

如果我将以下代码 sn-p 添加到“正常”片段,它会在往返片段导航时按预期启动和取消,但如果我将其添加到视图寻呼机 2 内的片段,它甚至不会被取消虽然调用了fragmens onPause 方法。这是设计使然还是我遗漏了什么?

lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        try {
            while (isActive) {
                println("Fragment alive....")
                delay(1000)
            }
        } catch (ex: CancellationException) {
            println("Cancelled fragment...")
            throw ex
        }
    }
}

【问题讨论】:

  • 这取决于您的 ViewPager2 适配器实现,在实现一些回收时可能是正确的行为

标签: android android-lifecycle android-viewpager2


【解决方案1】:

我不确定我的问题是否正确,但是如果您希望在 Fragment 可见时执行您的代码,那么我已经可以看出您正在中继错误的生命周期事件,因为您需要使用 @ 987654323@。使用它,您的代码将在 Fragment 为 visible 时立即开始执行,并在暂停时被取消。 使用repeatOnLifecycle(Lifecycle.State.STARTED),您的代码将在 Fragment 启动(准备显示)时开始执行,并在它停止时被取消。

【讨论】:

  • 啊当然..愚蠢的错误。感谢您帮助我!
  • 发生在我们最好的人身上,不客气
  • @MuhannadFakhouri 你能检查一下这个issue
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多