java - Persisting fragment state -
i have frame layout in activity want display different fragments inside. have sliding drawer 3 options, each of lead fragment being loaded inside frame layout. use following accomplish this:
fragment nextfragment = determinefragmenttoswitchto(nextfragmenttag); transaction.replace(r.id.fragment_container, nextfragment);
the first method determines fragment need evaluating nextfragmenttag string , loading new fragment 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 approach creating new fragment each time , running through whole fragment lifecycle without saving state. if on student page , scrolling through student list , switch parent page, when go student page, reloads entire list (i fetching server) , looses place in it. how can persist state , sort of cache fragment in manager (if makes sense)?
you use fragmenttransaction's
hide(fragment)
, show(fragment)
methods, e.g.:
// in 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 same procedure other 2 fragments // suppose want begin teacherfragment on // display - in case hide studentfragment , // parentfragment: fragmenttransaction.hide(studentfragment); fragmenttransaction.hide(parentfragment); fragmentondisplay = teacherfragment; fragmenttransaction.commit(); }
now whenever need switch fragments, hide
fragment on display, , show
fragment need, e.g.:
... fragmenttransaction.hide(fragmentondisplay); fragmenttransaction.show(parentfragment); fragmentondisplay = parentfragment; fragmenttransaction.commit();
Comments
Post a Comment