导航架构片段重新加载问题 [英] Navigation Architecture Fragment Reload Problem

本文介绍了导航架构片段重新加载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在图库中使用导航架构,当我从片段A转到片段B,然后返回到A时,再次调用这3种方法,这将导致我的图库重新加载,我应该在哪里将数据分段加载,以便当我从B返回到A时不会调用我的方法? :

I am using Navigation Architecture in an image gallery, when I go from fragment A to B and then return back to A, these 3 methods are called again which will cause my gallery to reload, where I should load my data in fragment so when I come back from B to A my methods don't get called? :

  1. OnCreateView
  2. OnViewCreated
  3. OnResume

推荐答案

我也面临着同样的问题,我的片段(比如说片段A )在回来(通过从其他片段(片段B )中按下设备后退按钮.我试图找出有效的解决方案,但找不到相同的解决方案.目前,我已经使用Fragment生命周期完成了一个临时解决方案.当我们popBackStack()一个片段( Fragment B ),另一个即将出现的片段( Fragment A ),其onCreateView()onViewCreated()时,将被称为.因此,我已使用此生命周期管理状态.第一次时,我们的 Fragment A 将启动,其onAttach()函数将运行,在此我将片段状态保存为:

I am also facing the same problem where my fragment (Say Fragment A) is getting reloaded while coming back (via Device Back Button press) from other fragment (Fragment B). I have tried to find out the valid solution for this but not able to find the same. For the time being, I have done one temporary solution using Fragment lifecycle. When we popBackStack() a fragment (Fragment B), the other fragment (Fragment A) which is coming to foreground, its onCreateView() and onViewCreated() will be called. So I have managed the status using this lifecycle. When first time, our Fragment A will launch, its onAttach() function will run and in this I saved the fragment status as:

override fun onAttach(context: Context) {
    super.onAttach(context)
    fragmentStatus = "onAttach"
}

在onViewCreated()中,我将此状态更改为:

After in onViewCreated(), I changed this status to:

fragmentStatus = "onViewCreated"

onViewCreated()内部,我正在将该状态值检查为

And inside onViewCreated() I am checking for this status value as

if (fragmentStatus == "onAttach") {
        fragmentStatus = "onViewCreated"
//Write your code here for rest of the functionality
}

因此,现在只要此片段A出现在前景中,它始终会以onViewCreated的状态出现,直到该片段被销毁并重新启动为止.

So now whenever this Fragment A will come into foreground, it will always found status as onViewCreated, until this fragment get destroyed and restarted.

注意:这是一个临时解决方案,以避免在Fragment中重新加载您的工作,但是系统会根据其要求重新启动该Fragment.

这篇关于导航架构片段重新加载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆