你的位置:首页 > 操作系统

[操作系统]android 切换fragment的两种方式


使用add方法切换时:
载入Fragment1
Fragment1 onCreate
Fragment1 onCreateView
Fragment1 onStart
Fragment1 onResume
用以下代码切到Fragment2:

  1. FragmentTransaction ft = getFragmentManager().beginTransaction();
  2. ft.hide(Fragment1);
  3. ft.add(R.id.simple_fragment, Fragment2);
  4. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  5. ft.commit();

Fragment1不走任何生命周期,但会调onHiddenChanged方法
Fragment2 onCreate
Fragment2 onCreateView
Fragment2 onStart
Fragment2 onResume
回到Fragment1,Remove Fragment2:

  1. FragmentTransaction ft = getFragmentManager().beginTransaction();
  2. ft.remove(Fragment2);
  3. ft.show(Fragment1);
  4. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  5. ft.commit();

Fragment1还是不走任何生命周期,调onHiddenChanged方法
Fragment2 onPause
Fragment2 onStop
Fragment2 onDestoryView
Fragment2 onDestory
用这种方法切换,Fragment在隐藏时并不会走onDestoryView,所以显示时也不会走onCreateView,所有View都一直保存在内存中。
用replace方法:
载入Fragment1生命周期与上面相同:
Fragment1 onCreate
Fragment1 onCreateView
Fragment1 onStart
Fragment1 onResume
切到Fragment2:

  1. FragmentTransaction ft = getFragmentManager().beginTransaction();
  2. ft.replace(R.id.simple_fragment, Fragment2);
  3. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  4. ft.commit();

这次的Fragment1走生命周期了
Fragment1 onPause
Fragment1 onStop
Fragment1 onDestoryView
Fragment1 onDestory
Fragment2 onCreate
Fragment2 onCreateView
Fragment2 onStart
Fragment2 onResume
真实打印出来可能是Fragment1和Fragment2混在一起的,可以看到,Fragment1走了onDestory,被完全回收了!
再切回到Fragment1

  1. FragmentTransaction ft = getFragmentManager().beginTransaction();
  2. ft.replace(R.id.simple_fragment, Fragment1);
  3. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  4. ft.commit();

Fragment1 onCreate
Fragment1 onCreateView
Fragment1 onStart
Fragment1 onResume
Fragment2 onPause
Fragment2 onStop
Fragment2 onDestoryView
Fragment2 onDestory
Fragment1因为已经被回收,又走onCreate,Fragment2被回收。