【问题标题】:Issue with the Life Cycle flow execution with Fragment and Activity使用 Fragment 和 Activity 执行生命周期流程的问题
【发布时间】:2021-06-04 21:03:06
【问题描述】:

有一个名为HomeActivity的Activity。

在片段容器中添加了一个名为 MyProfileFragment 的片段。

现在,在其上添加了一个 UserLocationFragment。

现在,在 UserLocationFragment 内部,我正在打开 google place api 对话框以选择特定地址。我已经覆盖了 OnActivityResult 方法来在 UserLocationFragment

中设置结果

问题是:

MyProfileFragment 的 onResume() 方法在调用,设置地址后。意味着当我来到 UserLocationFragment

内部覆盖的 onActivityResult 方法时

可能是什么问题?或者我应该怎么做才能避免调用这个名为 MyProfileFragment 的以前 Fragment 的 onResume() 方法?

谢谢。

【问题讨论】:

  • 可以分享MyProfileFragment和UserLocationFragment的代码吗?它将帮助我了解您想要实现的目标。
  • @MayurGajra 请检查一下,我已经添加了代码。

标签: android android-fragments android-activity fragment


【解决方案1】:

从您的代码看来,您正在使用意图来启动自动完成活动。因此,根据 android 生命周期,当您移动到 ​​AutocompleteActivity 时,您的 HomeActivity 将停止,它的子组件也是如此Fragments。因此,在MyProfileFragment 上也会调用 onResume。这是我们无法避免的。

因此,我不建议在 onResume 上进行 API 调用。

但是,如果这是您的用例,并且您必须在 onResume 中执行此操作,我建议您在 java 中使用 Global public static 变量或在 kotlin 中使用 companion object 变量作为标志,就像您评论过 isRefreshData 一样控制何时应该进行 API 调用。当您认为合适的时候将其设为true,并在获得结果时切换到false。

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2014-06-08
    相关资源
    最近更新 更多