Android solves multiple fragment transitions when layout re-instantiation issues

Source: Internet
Author: User



This article draws from: http://www.jianshu.com/p/d9143a92ad94



As for the use of fragment not much to say, straight to the subject,





Layout file:

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Xmlns:tools="Http://schemas.android.com/tools"android:layout_width="Match_parent"  android:layout_height="Match_parent"android:orientation="Vertical"  Tools:context="fan.fragmentdemo.MainActivity">                    Navigation bar<linearlayout  android: Layout_width  = "match_parent"  android:layout_ Height  = "48DP"  android:orientation  =< Span class= "Hljs-value" > "horizontal" ;         <textview  android:layout _width  = "0DP"  android:layout_weight  =< Span class= "Hljs-value" > "1"  android:layout_height  =" match_parent " android:text  =" first " android:id  = "@+id/tv_one"  android:gravity  = "center" />         <textview  android:layout _width  = "1DP"  android:layout_height  =< Span class= "Hljs-value" > "match_parent"  android:background  = "#EEE" />         <textview  android:layout _width  = "0DP"  android:layout_weight  =< Span class= "Hljs-value" > "1"  android:layout_height  =" match_parent " android:text  =" second " android:id  = "@+id/tv_two"  android:gravity  = "center" />         <textview  android:layout _width  = "1DP"  android:layout_height  =< Span class= "Hljs-value" > "match_parent"  android:background  = "#EEE" />         <TextViewandroid:layout_width="0DP"android:layout_weight="1"  android:layout_height="Match_parent"android:text="Third"Android:id ="@+id/tv_three"android:gravity="center" />                                                                            </linearlayout>Content Area<framelayoutandroid:id="@+id/content"android:background="#EEE"  android:layout_width="Match_parent"android:layout_height="Match_parent" />                                </linearlayout>





Layout Preview Diagram:








Previously written multiple fragment switching is often used this way to switch fragment:

/**  * 使用replace切换页面  * 显示fragment  */privatevoidshowFragment(Fragment fg){     FragmentTransaction transaction = fragmentManager.beginTransaction();     transaction.replace(R.id.content, fg);     transaction.commit(); }





Replace (): This method is only an easy way to use when the previous fragment is no longer needed, and the drawback is that if you need to reuse the fragment, you need to reload it every time. For example, I enter the information in the first fragment, after switching the second fragment and then switch back, it will result in data loss, as follows:









Also, if each switch is instantiated once, the stack under the Fragmentmanager management will be full, eventually will cause the phone to lag, which is obviously not the correct fragment use posture, then we need to use show (), Hide (), add (), The correct way to switch is add (), hide (), add () another fragment; When switching again, just hide () and show () another line, the code is modified as follows:

/**  * 使用show() hide()切换页面  * 显示fragment  */privatevoidshowFragment(Fragment fg){     FragmentTransaction transaction = fragmentManager.beginTransaction();     //如果之前没有添加过     if(!fg.isAdded()){         transaction                 .hide(currentFragment)                 .add(R.id.content,fg);     }else{         transaction                 .hide(currentFragment)                 .show(fg);     }    //全局变量,记录当前显示的fragment     currentFragment = fg;     transaction.commit(); }



Effect:







Yes, you can see that even if you switch to another fragment, and then switch back, the data still exists, which avoids the fragment of the layout re-instantiation when switching.




The Android app has a special situation, that is, when the app is running in the background, when the system resources are tight, the resources of the app are all recycled (the process of killing the app), then the app will restart when it returns to the foreground from the backstage. This is referred to as the following: "Memory restart". (configuration changes such as screen rotation can also cause the current activity to restart, essentially similar to "memory restart")

Before the system to recycle the app, the system will save the state of activity, the activity of the Fragmentmanager is responsible for the activity of the fragment saved up. After a "memory reboot", the activity recovery is resumed from the top of the stack, and fragment will recover immediately after the host activity's OnCreate method call




When we do not exit the software, just hang in the background to do other things, when the system memory is not enough to recycle our app, and then switch back, the app's several fragment interface will overlap. Such as:







As you can see, all three fragment are stacked together, and clicking on the menu above does not eliminate overlap. Obviously, this is not what we want, OK, continue to solve the problem, using Findfragmentbytag: That is, add () or replace () binding a tag, generally we use fragment class as tag, and then in the event of "memory Restart", The corresponding fragment is found through Findfragmentbytag and hide () requires a hidden fragment. , modify the following:

/**  * 使用show() hide()切换页面  * 显示fragment  */privatevoidshowFragment(Fragment fg){     FragmentTransaction transaction = fragmentManager.beginTransaction();     //如果之前没有添加过     if(!fg.isAdded()){         transaction                 .hide(currentFragment)                 .add(R.id.content,fg,fg.getClass().getName());  //第三个参数为当前的fragment绑定一个tag,tag为当前绑定fragment的类名     }else{         transaction                 .hide(currentFragment)                 .show(fg);     }     currentFragment = fg;     transaction.commit(); }





Don't worry, it's not over yet. Add the code in the current activity's onCreate() method:

if(Savedinstancestate! =NULL) {//"Memory Restart" is called   //From Fragmentmanager inside find fragmentFgone = (onefragment) fragmentmanager.findfragmentbytag (onefragment.class. GetName ()); Fgtwo = (twofragment) fragmentmanager.findfragmentbytag (twofragment.class. GetName ()); Fgthree = (threefragment) fragmentmanager.findfragmentbytag (threefragment.class. GetName ());//Resolve overlapping issues show inside can specify the page to restoreFragmentmanager.begintransaction (). Show (Fgone). Hide (Fgtwo). Hide (Fgthree). Commi T ();//Record the currently displayed fragmentCurrentfragment = Fgone;}Else{//call at normal startupFgone =NewOnefragment (); Fgtwo =NewTwofragment (); Fgthree =NewThreefragment (); Showfragment (Fgone);}





OK, when the app backend experience "memory restart" situation, and then return to our app, will be restored to the show(fgOne) page, and will not cause overlapping problems!


Obviously, this end is immoral, because someone will ask, if you want to record the current exit status so that the next time you restore the fragment page directly to show what to do, well, for this problem, we can in the activity of the onSaveInstanceState() method to record "Memory Restart" Before the fragment page is then oncreate() taken out in, according to the saved page to display to the specified fragment, the code is as follows:


@OverrideprotectedvoidonSaveInstanceState(Bundle outState) {    //“内存重启”时保存当前的fragment名字    outState.putString(STATE_FRAGMENT_SHOW,currentFragment.getClass().getName());    super.onSaveInstanceState(outState);}





Then add it in the oncreate() method (modify the code above)

if (savedinstancestate! = null) {//"memory restart" when calling//getting "memory restart" when saving fragment name String Savename = savedinstancestate. getString(state_fragment_show);Find fragment from Fragmentmanager Fgone = (onefragment) fragmentmanager. Findfragmentbytag(onefragment. Class. GetName());Fgtwo = (twofragment) fragmentmanager. Findfragmentbytag(twofragment. Class. GetName());Fgthree = (threefragment) fragmentmanager. Findfragmentbytag(threefragment. Class. GetName());If empty, the default action is if (textutils. IsEmpty(Savename)) {//Resolve overlapping issues Fragmentmanager. BeginTransaction(). Show(Fgone). Hide(Fgtwo). Hide(Fgthree). Commit();Record the currently displayed fragment Currentfragment = Fgone;}else{if (savename. Equals(Fgone. GetClass(). GetName())) {//if it is onefragment//solve overlap problem before launch Fragmentmanager. BeginTransaction(). Show(Fgone). Hide(Fgtwo). Hide(Fgthree). Commit();Record the currently displayed fragment Currentfragment = Fgone;}else if (savename. Equals(Fgtwo. GetClass(). GetName())) {//if it is twofragment//solve overlap problem before launch Fragmentmanager. BeginTransaction(). Show(Fgtwo). Hide(Fgone). Hide(Fgthree). Commit();Record the currently displayed fragment Currentfragment = Fgtwo;}else{//threefragment//Resolve overlapping issues before rollout Fragmentmanager. BeginTransaction(). Show(Fgthree). Hide(Fgtwo). Hide(Fgone). Commit();Record the currently displayed fragment Currentfragment = Fgthree;}}}else{//Call Fgone at normal startup = new Onefragment ();Fgtwo = new Twofragment ();Fgthree = new Threefragment ();Showfragment (Fgone);}





OK, so that we can, by saving the currently displayed class name of the fragment, when we in the second fragment page background, wait until "memory restart" when returning to the app, based on the previously saved class name to determine the loading of the specified fragment, and the overlap problem is solved!

This chapter code and APK: click Free download





In the end, say one thing:

Getactivity () NULL pointer
You may have encountered a getactivity () return null, or normally well-run code, after "Memory restart", where the call to Getactivity () returned NULL, reported a null pointer exception.

In most cases, the reason: when you call Getactivity (), the current fragment has Ondetach () the host activity.
For example: After you pop the fragment, the fragment's asynchronous task is still executing, and the Getactivity () method is called after execution completes, so the pointer is empty.

Workaround:
More "secure" approach: (for fragment has ondetach this situation, we should avoid to call the host activity object after this, such as canceling these asynchronous tasks, but our team may have a careless situation, so the following gives this scheme will ensure security)

Set a global variable for activity mactivity in the fragment base class, assign a value to Onattach (activity activity), use mactivity instead of getactivity (), Ensure that the fragment still holds references to activity even after Ondetach (there is a risk of memory leaks, but this is "safe" compared to the null pointer flashback), i.e.:

protected Activity mActivity;@OverridepublicvoidonAttach(Activity activity) {    super.onAttach(activity);    this.mActivity = activity;}/***  如果你用了support 23的库,上面的方法会提示过时,有强迫症的小伙伴,可以用下面的方法代替*/@OverridepublicvoidonAttach(Context context) {    super.onAttach(context);    this.mActivity = (Activity)context;}

Android solves multiple fragment transitions when layout re-instantiation issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.