John Baum
John Baum

Reputation: 3331

Persisting fragment state

I have a frame layout in an activity to which i want to display different fragments inside. I have a sliding drawer with 3 options, each of which lead to a fragment being loaded inside the frame layout. Currently i use the following to accomplish this:

Fragment nextFragment = determineFragmentToSwitchTo(nextFragmentTag);
transaction.replace(R.id.fragment_container, nextFragment);

The first method determines what fragment i need by evaluating the nextFragmentTag string and loading a new fragment like so:

if (fragmentTag.equals(Constants.STUDENTPAGE))
     nextFragment = new StudentFragment();
else if (fragmentTag.equals(Constants.TEACHERPAGE))
     nextFragment = new TeacherFragment();
else if (fragmentTag.equals(Constants.PARENTPAGE))
     nextFragment = new ParentFragment();

Clearly this approach is creating a new fragment each time and running through the whole fragment lifecycle without saving state. So if i am on the student page and scrolling through the student list and i switch to the parent page, when i go back to the student page, it reloads the entire list (i am fetching it from a server) and looses my place in it. How can i get it to persist state and sort of cache that fragment in the manager (if that makes sense)?

Upvotes: 1

Views: 121

Answers (1)

k29
k29

Reputation: 1909

You could use the FragmentTransaction's hide(Fragment) and show(Fragment) methods, e.g.:

// In the parent Activity 

StudentFragment studentFragment;
TeacherFragment teacherFragment;
ParentFragment parentFragment;
Fragment fragmentOnDisplay;

@Override
protected void onCreate(Bundle savedInstanceState) {

   // Initialize fragmentManager, fragmentTransaction, etc.

   studentFragment = (StudentFragment) fragmentManager.findFragmentByTag(Constants.STUDENTPAGE);
   if (studentFragment == null) {
      studentFragment = new StudentFragment ();
      fragmentTransaction.add(R.id.your_frame_layout, studentFragment, Constants.STUDENTPAGE);
   }

   // repeat the same procedure for the other two fragments     

   // Suppose you want to begin with the teacherFragment on 
   // display - in that case hide the studentFragment and 
   // the parentFragment:             

   fragmentTransaction.hide(studentFragment);
   fragmentTransaction.hide(parentFragment);
   fragmentOnDisplay = teacherFragment;
   fragmentTransaction.commit();
}

Now whenever you need to switch your fragments, simply hide the fragment on display, and show the fragment you need, e.g.:

...
fragmentTransaction.hide(fragmentOnDisplay);
fragmentTransaction.show(parentFragment);
fragmentOnDisplay = parentFragment;
fragmentTransaction.commit();

Upvotes: 1

Related Questions