In the example on using fragments in the Android docs, when the application is in ‘dualview’ mode, the details fragment is recreated whenever the application needs to show details for a different title. FragmentTransaction.replace() is used to swap out each old details fragment instance with a new one.
Is this recommended practice? Isn’t it wasteful to create a new UI instance when the real intent (no pun intended) is to update what the UI shows, not the UI itself. It seems to me the only reason to create new instances is if one intends to add them to the backstack so the user can retrace steps. Otherwise, is it safe/advisable to update a fragment directly?
In the case of the example, it would mean a method along the lines of DetailsFragment.setShownIndex(). This would be called, passing in the new title index, instead of recreating DetailsFragment.
Suppose we have a version of the example where one activity manages both fragments, but only shows one at a time, swapping each fragment out as needed. Would it be ok for the activity to create an instance of each fragment, retain references to each, and then simply add or remove these two instances from itself as needed?
One possibly sticky consequence of this would be that, when the titles fragment is in resumed state (i.e. in the ‘foreground’), selecting a title will result in a call to DetailsFragment.setShownIndex() at a time when the details fragment is in stopped state.
Good idea? Bad idea?
Thanks in advance.
Like you said, the main reason to create new Fragment instances is for ease of using the back stack. It is also perfectly safe to reuse an existing Fragment (looking it up using either
FragmentManager.findFragmentById()orFragmentManager.findFragmentByTag()). Sometimes you’ll need to make good use of the Fragment methods likeisVisible(),isRemoving()etc. so you don’t illegally reference UI components when theDetailsFragmentisstopped.Anyway in your proposed single-pane Activity with 2 fragments, your
setShownIndexmethod could set a private field inDetailsFragmentwhich is loaded inonCreateVieworonActivityCreated.e.g.,
In both cases, whether df is newly created or reused,
onCreateViewandonActivityCreatedwill be called when theDetailsFragmentgets added to the container.But if you want a back stack, I highly recommend just creating new instances, otherwise you’re just implementing your own back stack for the contents of the
DetailsFragment.