Best practices for managing multiple Fragment in Android to perfectly solve the problem of saving status and shadow

Source: Internet
Author: User

Best practices for managing multiple Fragment in Android to perfectly solve the problem of saving status and shadow
Since Fragment was introduced in Android 3.0, it has been used more frequently. The benefits brought by Fragment are self-evident, solving the dynamic and flexible uidesign of different screen resolutions. However, in the Activity management of multiple Fragment, these problems are usually encountered: 1. Fragment state saving 2. Fragment's duplicate influence, of course, these problems have also appeared in my development process, although some problems can be solved through various means, they are always solved perfectly at the same time. Recently, many official documents have been consulted for the project (Android official documents also gradually contain Chinese documents, so I am a big Google developer, Don't be edevil ~~), These problems have finally been completely solved. Device: nexus 5 conditions: 1. Enable the "do not retain Activity" (in the developer option, it is mainly used to simulate the Activity to be recycled in a timely manner) 2. Disable the "do not retain Activity" (normally) result: No problem is found. Due to limited devices, please reply below if you find any problem on other devices! First, let me explain the reasons for the above problem: 1. Sometimes, we need to switch between multiple Fragment and save the status of each Fragment. The official method is to use replace () to replace Fragment, but the call of replace () will cause the onCreteView () of Fragment to be called, so the current status cannot be saved during interface switching. Therefore, add (), hide (), and show () are usually used together to save the Fragment state. The following is a code snippet:

Private void setTabSelection (int position) {// record position this. position = position; // change the status of the button in the bottom navigation bar. changeButtonStatus (position); FragmentTransaction transaction = fragmentManager. beginTransaction (); // hide all Fragment first to prevent multiple Fragment display on the interface. hideFragments (transaction); switch (position) {case TAB_HOME: btnHomePager. setSelected (true); btnShoppingCart. setSelected (false); btnMine. setSelected (false); if (homeFragment = null) {homeFragment = new HomePagerFragment (); transaction. add (R. id. fragment_container, homeFragment);} else {transaction. show (homeFragment);} break; case TAB_SHOP: btnHomePager. setSelected (false); btnShoppingCart. setSelected (true); btnMine. setSelected (false); if (shoppingFragment = null) {shoppingFragment = new ShoppingCartFragment (); transaction. add (R. id. fragment_container, shoppingFragment);} else {transaction. show (shoppingFragment);} break; case TAB_MINE: btnHomePager. setSelected (false); btnShoppingCart. setSelected (false); btnMine. setSelected (true); if (mineFragment = null) {mineFragment = new MineFragment (); transaction. add (R. id. fragment_container, mineFragment);} else {transaction. show (mineFragment);} break;} transaction. commitAllowingStateLoss ();}

 

2. The second problem occurs because the Fragment status is saved. When the system memory is insufficient and the Fragment host Activity is recycled, the Fragment instance is not recycled. When the Activity is recycled by the system, the onSaveInstance () method is called to save the View Hierarchy. Therefore, when the Activity is rebuilt through navigation, the previously instantiated Fragment will still appear in the Activity. However, it can be seen from the code above that the new Fragment is re-constructed, in summary, these factors cause multiple Fragment to overlap. I tried many ways to solve this problem. For example, in onSaveInstance (), remove () All non-empty Fragment, and then in onRestoreInstanceState () in step 1. When I opened the "do not retain activity", the effect was very satisfactory. However, when I closed the "do not retain activity", the problem occurred. When you jump to another Activity, open the multi-task window, return to the Home screen, and then return, there is no Fragment at all. As a result, I tracked the methods onSaveInstanceState () and onRestoreInstanceState. The onSaveInstanceState () that was originally called only when the system recycled the Activity because of the memory is also called during the operations such as redirecting to another Activity, opening the multi-task window, and returning the Home to the Home screen, however, onRestoreInstanceState () is not called when it returns to Activity again. In addition, I found in onResume () that the previous Fragment was only removed and not empty. Therefore, even if you execute the Fragment method created in problem 1 in onResume (), it will not help. Therefore, a failure is declared through remove. Then, we found that there is a super in onSaveInstanceState () in the Activity. onRestoreInstanceState (savedInstanceState), Google's explanation for this sentence is "Always call the superclass so it can save the view hierarchy state ", this code is always executed to call the parent class to save the view layer status ". As a matter of fact, we can see from here that this sentence has caused the appearance of a shadow, so I deleted this sentence, and then onCreate () and onRestoreInstanceState () use the Fragment method in question 1 at the same time, and then save the switchover status to find that the result is perfect. The Code is as follows:
// Record the location of Fragment private int position = 0; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_index); setTabSelection (position) ;}@ Override protected void onRestoreInstanceState (Bundle savedInstanceState) {position = savedInstanceState. getInt ("position"); setTabSelection (position); super. onRestoreInstanceState (savedInstanceState) ;}@ Override protected void onSaveInstanceState (Bundle outState) {// record the current position outState. putInt ("position", position );}

 

 

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.