使用Fragment和Activity执行生命周期流程的问题 [英] Issue with the Life Cycle flow execution with Fragment and Activity
问题描述
有一个名为 HomeActivity的活动.
名为 MyProfileFragment 的片段被添加到片段容器中.
A Fragment named MyProfileFragment is added inside fragment container.
现在,在其上添加了 UserLocationFragment .
现在,在UserLocationFragment内部,我正在打开google place api对话框以选择特定的地址.我有重写OnActivityResult方法来在 UserLocationFragment
Now, Inside UserLocationFragment, I am opening google place api dialog to select the particular address. I have override OnActivityResult method to set the result inside UserLocationFragment
问题是:
设置地址后,将调用MyProfileFragment的onResume()方法.表示当我使用在 UserLocationFragment
The MyProfileFragment's onResume() method is calling, After setting the address. means when I come to onActivityResult method which is override inside UserLocationFragment
可能是什么问题?还是应避免调用以前的片段的 onResume()方法,该方法名为 MyProfileFragment ?
What might be the issue ? or What I should do to avoid the calling of this previous Fragment's onResume() method named MyProfileFragment ?
谢谢.
推荐答案
从您的代码看来,您似乎是在使用意图启动自动完成活动.因此,根据android的生命周期,当您移至 AutocompleteActivity
时,您的 HomeActivity
会停止,并且它的子组件(即 Fragments
)以及您返回时也会停止可以看到 HomeActivity
继续执行,所有子 Fragments
也是如此.因此,onResume也将在 MyProfileFragment
上调用.我们无法避免这种情况.
From your code it seems you're using an intent to launch the autocomplete activity. So according to the android lifecycle your HomeActivity
is stopped when you move to AutocompleteActivity
and so are it's child components i.e Fragments
and when you come back and the HomeActivity
is visible it resumes and so do the all the child Fragments
. Hence, The onResume is called on the MyProfileFragment
as well. We can not avoid this.
由于这个原因,我不建议在 onResume
上进行API调用.
For this reason, I would not recommend making API calls on onResume
.
但是,如果这是您的用例,并且您必须在 onResume
内部执行,则建议在Java或 companion对象
public static 变量> kotlin中的变量作为标记,就像您已经注释了 isRefreshData
一样,它使您可以控制何时进行API调用.在您认为合适的时候将其设置为 true
,并在获得结果时切换为 false
.
But if it's your use case and you must do it inside onResume
I would recommend having a Global public static
variable in java or companion object
variable in kotlin as a flag like you have commented isRefreshData
which gives you control when you should make API call. Make it true
when you think it's right time and switch to false
when you get the result.
这篇关于使用Fragment和Activity执行生命周期流程的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!