Android开发之Fragment几种加载方式的优化和对比

来源:互联网 发布:mac 桌面文件夹整理 编辑:程序博客网 时间:2024/05/21 21:33

本文转自   http://blog.csdn.net/u012915455/article/details/53488079


1.利用replace

频繁地replace Fragment来切换,会不断创建新实例,销毁旧的,浪费资源,无法重用。

在onCreate 里面初始化一个fragmentOne

 FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.id_content,fragmentOne).show(fragmentOne).commit();
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

需要切换fragmentTwo的时候

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.id_content, fragmentTwo); ft.commit();
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

2.利用show、hide

如果Fragment需要重用或者不断切换,可以使用该方法提高性能。

if (!fragment.isAdded())  //判断有没有加载过{    getSupportFragmentManager().beginTransaction().hide(temp).add(R.id.id_content, fragment).commit();}else{    getSupportFragmentManager().beginTransaction().hide(temp).show(fragment).commit();}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.回退栈

像Activity一样通过栈的方式来管理Fragment,和replace相比 增加了栈的管理

fragmentOne 转 FragmentThree FragmentThree 返回fragmentOne 实现

fragmentOne跳转:

  FragmentThree fragment = new FragmentThree();  FragmentManager fragmentManager = getActivity().getSupportFragmentManager();  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  fragmentTransaction.replace(R.id.id_content,fragment);  //将当前的事务添加到了回退栈  fragmentTransaction.addToBackStack(null);  fragmentTransaction.commit();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

FragmentThree返回上一层:

 FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.popBackStack();

0 0
原创粉丝点击