Android fragment uses replace and saves the status
Fragment plays an important role in development. It is very important to master its lifecycle and usage features. For example, templates often used in development:
Click the menu and the center content follows the menu changes. However, when switching between a single menu, you need to save the previously entered information or other statuses. If you use the Fragment hide environment? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vc2hvd7e9t6jI58/Co7o8L3A + CjxwPjxwcmUgY2xhc3M9" brush: java; "> FragmentTransaction transaction = fragmentManager. beginTransaction (); transaction. setCustomAnimations (R. anim. right_in, R. anim. left_fadeout, R. anim. right_fadein, R. anim. left_fadeout); transaction. hide (oldFragment); transaction. show (newFragment); transaction. commit ();
However, using this method may have A Bug: when switching A menu, such as A-B-C switching, when displaying C content, the information of Components A or B may also be displayed, it can also respond to events, which are intolerable for applications!
The reason for this problem has not been found. If you know why, please ask for a popular science...
Another method is to replace hide/show with replace. The focus is to call FragmentTransaction. addToBackStack () to save the fragment status. The Code is as follows:
Private void replaceContainer (MenuItems menuItem) {FragmentTransaction transaction = fragmentManager. beginTransaction (); transaction. setCustomAnimations (R. anim. right_in, R. anim. left_fadeout, R. anim. right_fadein, R. anim. left_fadeout); Fragment fragment = retrieveFromCache (menuItem); // fragment has not been instantiated. A new one is added to FragmentTransaction and the fragment state if (null = fragment) is saved) {try {fragment = menuItem. getClazz (). NewInstance (); transaction. addToBackStack (null);} catch (Exception e) {Log. e (TAG, "instantiation menu failed"); return ;}} transaction. replace (R. id. content_frame, fragment); transaction. commit ();} private Fragment retrieveFromCache (MenuItems menuItem) {// get the existing fragment object from fragmentManager for (Fragment backFragment: fragmentManager. getFragments () {if (null! = BackFragment & menuItem. getClazz (). equals (backFragment. getClass () {return backFragment ;}} return null ;}
Not only can the fragment status be saved, but the fragment lifecycle can also be moved normally !! Remember that FragmentTransaction. addToBackStack () is very important!