Android manages multiple fragment (handles the activity being recycled)

Source: Internet
Author: User

Do a long time project, due to progress, also didn't how Bambo to write blog. But the project is to rush, not a mouthful can swallow, to slowly. Now that you're slow, take some time to write something. There are several thorny issues in the project. A few of them were solved by me. One of these is the management problem of multiple fragment. Can only say that I am a novice Android, nor how to learn Android, so some things can only be explored in the project, to use which to learn which, fortunately I also probably know what to use, which is to be learned.

Scenario One: using multiple fragment in an activity, click Toggle Fragment in tab form. A total of 4 fragment were used, and all fragment references were saved with a global fragment array. Complete the instantiation in the OnCreate method (the first fragment is displayed by default).
java
mContentFragments = new BaseFragment[4];

This will cause a problem, such as: Now you switch to the 2nd fragment, the application switch to the day after tomorrow, this activity is recycled in the background, and then you do not know, you cut back to the application, activity and re-call the activity method. Then you're stuck, because the application goes back to the first fragment.
solution (if there are other solutions to the master, please inform the next!) ):
"' Flow
St=>start: App goes backstage
E=>end: Back to normal application
Op1=>operation: Call Onsaveinstancestate hold State
Cond=>condition:aty was killed in the background?
Op2=>operation: Call onrestoreinstancestate Recovery state
St->op1->cond
Cond (yes)->op2->e
Cond (NO)->e

  
  1. 由于我们一旦按了Home键,应用会转后台,aty会自动调用onSaveInstanceState保持状态,所以我们在onSaveInstanceState的方法里保存状态。aty在后台被杀死后,onSaveInstanceState中有保存状态,回到aty时会自动调用onRestoreInstanceState方法。
  2. ```java
  3. @Override
  4. protected void onSaveInstanceState(Bundle outState)
  5. {
  6. // mCurrentPosition表示当前切换的fragment的数组下标
  7. outState.putInt(POSITIONKEY, mCurrentPosition);
  8. //super.onSaveInstanceState(outState); 总是执行这句代码来调用父类去保存视图层的状态,会导致fragmen重影,不能正常恢复状态
  9. }
  10. @Override
  11. protected void onRestoreInstanceState(Bundle savedInstanceState)
  12. {
  13. // 获取保存的数组下标
  14. mCurrentPosition=savedInstanceState.getInt(POSITIONKEY);
  15. // 回复视图状态,恢复为fragmen的切换状态
  16. changeTabView(savedInstanceState.getInt(POSITIONKEY));
  17. super.onRestoreInstanceState(savedInstanceState);
  18. }
  19. ```
  20. **情景二:**aty被回收了,fragment没被回收(还在内存中,只是我们没有它们的引用)!
  21. 先晾一下切换fragment的代码先:
  22. ```java
  23. public void changeFragment(int resView, Fragment targetFragment)
  24. {
  25. if (targetFragment.equals(currentFragment))
  26. {
  27. return;
  28. }
  29. FragmentTransaction transaction = getFragmentManager()
  30. .beginTransaction();
  31. if (!targetFragment.isAdded())
  32. {// 如果这个fragment没被添加过
  33. transaction.add(resView, targetFragment, targetFragment.getClass()
  34. .getName());
  35. }
  36. if (targetFragment.isHidden())
  37. {// 如果这个fragment是被隐藏的
  38. transaction.show(targetFragment);
  39. }
  40. if (currentFragment != null && currentFragment.isVisible())
  41. {// 隐藏当前显示的fragment
  42. transaction.hide(currentFragment);
  43. }
  44. currentFragment = targetFragment;
  45. // 提交了才算完成
  46. transaction.commit();
  47. }
  48. ```
  49. 在这里的代码,我使用的是FragmentTransaction里的add、show、hide方法,这样在fragment不多的情况下,可以保存fragment的状态,并提高了切换fragment的速度。但是这样的缺点在该情景下就有问题了。
  50. Atybe recycled,Fragmentstill in memory, inFragmentmanager, re-onCreate, and re-instantiate a new batch ofFragment, and then a callchangefragmentmethod. For example,Fragmentmanagerthere is aFragmenta, we re-instantiate aFragmenta. Because of twoFragmentaobject is not the same in the heap, sofragmenttransactionwill beAddthis newFragmentato theFragmentmanager(which will result inFragmentGhosting ), causing a memory leak.
  51. 所以,我们应该这么做(如有高手有其他解决办法请告知在下!):
  52. ```java
  53. @Override
  54. public void onCreate(Bundle savedInstanceState)
  55. {
  56. if (savedInstanceState != null)
  57. {
  58. // 防止fragment没被回收
  59. FragmentManager fm = getFragmentManager();
  60. mContentFragments = new BaseFragment[4];
  61. mContentFragments[0] = (BaseFragment) fm.findFragmentByTag(MainChatFragment2.class.getName());
  62. mContentFragments[1] = (BaseFragment) fm.findFragmentByTag(MainCircleFragment.class.getName());
  63. mContentFragments[2] = (BaseFragment) fm.findFragmentByTag(MainWallFragment.class.getName());
  64. mContentFragments[3] = (BaseFragment) fm.findFragmentByTag(MainFindFragment.class.getName());
  65. }
  66. super.onCreate(savedInstanceState);
  67. }


From for notes (Wiz)

Android manages multiple fragment (handles the activity being recycled)

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.