问题
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