Fragment's position is important in development, mastering its lifecycle and using features, such as templates that are commonly used in development:
Click the menu, the center content follows the menu changes, but when switching between the menus, you need to save the previously entered information or other state, if the Hide/show method using fragment is as follows:
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 can be a bug: When the menu switch, such as a-b-c switch, when the C content is displayed, the information of a or B components may be displayed, and can also respond to events, but it is not tolerated for the application!
As for the reasons why this problem has not been investigated, if you know, ask for science ...
Another way is to replace hide/show with replace, with the emphasis on calling Fragmenttransaction.addtobackstack () to save the fragment state, using the following code:
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 is not instantiated, new is added to the fragmenttransaction, and the state of Fragment is saved if ( NULL = = fragment) {try {fragment = Menuitem.getclazz (). newinstance (); Transaction.addtobackstack (null);} catch ( Exception e) {log.e (TAG, "Instantiation of Menu Failed"); return;}} Transaction.replace (R.id.content_frame, fragment); Transaction.commit ();} Private Fragment Retrievefromcache (MenuItems menuItem) {//Get existing Fragmentmanager objects from Fragment for (Fragment backfragment : Fragmentmanager.getfragments ()) {if (null! = backfragment&& Menuitem.getclazz (). Equals ( Backfragment.getclass ())) {return backfragment;}} return null;}
Not only can save the state of fragment, and fragment life cycle can also move normally!! Remember Fragmenttransaction.addtobackstack () This is very important oh!
Android fragment use replace and save state