Can I create my UI fragment in my activity's onStart()?

∥☆過路亽.° 提交于 2019-12-24 05:59:46

问题


I have an activity with a launchMode of singleTop but I want it to refresh when I go up to it from a child activity. Currently, because my fragment (which contains the UI) is instantiated in the activity's onCreate(), the UI doesn't reload when returning to it. But if I instantiated the fragment in onStart() it would be called when the activity is restarted. While I've gained understanding of the Activity lifecycle, I still don't fully understand how it and the Fragment lifecycle must coexist. I instantiate the fragment in the activity's onCreate() because that's what the tutorial app did.

Anyway, would this work?

I'm asking this in search of a potential solution to this question, which I asked but no one has answered. Thanks.


回答1:


You can do that, but that's not efficient.

I would suggest to create a refresh method inside your fragment, and that refresh method can update some UI components in your fragment, which is very fast and simple. In your activity onStart(), you can find the fragment (that you instantiated in onCreate) with the fragment manager and call the fragment's refresh. One of the reason is efficiency if you don't need to recreate a fragment, then avoid it. Instantiate new fragment takes time.

Bonus: you can set the criteria in the onStart() to determine if you really need the refresh, ie, it has been refreshed 2 seconds ago, do you really want to refresh again?



来源:https://stackoverflow.com/questions/23372201/can-i-create-my-ui-fragment-in-my-activitys-onstart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!