I’m creating a tablet optimised application using fragments. I have a thin navigation fragment down the left hand side with buttons to controls what fragments will be loaded into the two ViewGroup containers which take up the rest of the screen.
For example, if a button in the navigation fragment is pressed, the 1st container will be loaded with an item list fragment (eg for settings, customers etc) and the second container will be loaded with fragment to show the item details.
Since I want to retain the fragments in memory (so, when navigating from Settings to Customers and then back to Settings, the previous Settings fragments should be there so the user doesn’t lose where they were up to) – I have created fragments instance variables for the Activity
SettingsListFragment settingsListFragment;
SettingsDetailFragment settingsDetailFragment;
CustomerListFragment customerListFragment;
CustomerDetailFragment customerDetailFragment;
I then create these fragments when neccessary and replace the containers with the fragments as needed. eg.
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(settingsListFragment == null){
settingsListFragment = new SettingsListFragment();
}
fragmentTransaction.replace(R.id.fragment_container_left, settingsListFragment);
fragmentTransaction.commit();
My question is, how can I retain these instances accross an orientation change?
I’m assuming that I shouldn’t use the activities onRetainNonConfigurationInstance() method according to
http://developer.android.com/resources/articles/faster-screen-orientation-change.html because “Be very careful with the object you pass through onRetainNonConfigurationChange() …This means you should never pass a View, a Drawable, an Adapter, etc”
I’ve also attempted to get the Fragment from the fragment manager,
Fragment clf = fragmentManager.findFragmentByTag("CLIENT LIST");
but it comes back as null. I think it gets released after the fragment is replaced.
Thanks for any help/advice.
You can’t (or really shouldn’t) retain fragments in that way. I’m guessing it’s state you want to keep.
If you store your state in
onSaveInstanceState()you can later retrive it inonCreate()oronActivityCreate(). So after you go back (you’ll have to add theFragmentTransactionto the back stack) you can restore the state from the Bundle to which you saved it!FragmentManagerwill take care of handling configuration changes and restoring your fragments in their current views.