I'm using the compatibility package v4 in my project and I'm having an issue with keeping a Fragment
around after it's removed from view. I have my Activity
displaying 2 fragments...a menu frame on the left, content pane on the right. The menu frame has 3 different menus (Fragments) that can be displayed.
This is how I'm replacing the menu Fragment:
public void showMenuFragment( Fragment fragment, String tag ) {
showFragment( R.id.menu_frame, fragment, tag, false);
setLastMenuPushed( tag );
}
protected void showFragment( int resId, Fragment fragment, String tag, boolean addToBackStack ) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if ( fragmentManager.findFragmentByTag( tag ) != null && fragment.isAdded() ) {
transaction.remove( fragment );
}
transaction.replace( resId, fragment, tag ).setTransition( FragmentTransaction.TRANSIT_FRAGMENT_OPEN ).setBreadCrumbShortTitle( tag );
if ( addToBackStack ) {
transaction.addToBackStack( tag );
}
transaction.commit();
}
The menu Fragment
s require data to be loaded before it can be displayed, so I show a loading spinner. Once it's loaded the first time, I want to not have to ever load it a second time unless the Activity
is finished.
When I call showMenuFragment(...)
I try to pass in a Fragment
using FragmentManager.findFragmentByTag(String tag)
but it's always null
, so I have to make a new Fragment
every time I want to show a different menu.
My question is, how do I keep these Fragment
s around after they are replaced by other menus? I want to avoid keeping manual references to the Fragment
s because when the device is rotated, the instance of my Activity
class is destroyed and I would lose those references.
EDIT: To put in much simpler terms, I want the FragmentManager
to keep track of previous Fragment
s without having to add them to the back stack. I don't want to hit the back button and see the previous menu shown.