zoukankan      html  css  js  c++  java
  • 让多个Fragment 切换时不重新实例化

    在项目中需要进行Fragment的切换,一直都是用replace()方法来替换Fragment:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
        public void switchContent(Fragment fragment) {
            if(mContent != fragment) {
                mContent = fragment;
                mFragmentMan.beginTransaction()
                    .setCustomAnimations(android.R.anim.fade_in, R.anim.slide_out)
                    .replace(R.id.content_frame, fragment) // 替换Fragment,实现切换
                    .commit();
            }
        }
    

    但是,这样会有一个问题:
    每次切换的时候,Fragment都会重新实例化,重新加载一边数据,这样非常消耗性能和用户的数据流量。

    就想,如何让多个Fragment彼此切换时不重新实例化?

    翻看了Android官方Doc,和一些组件的源代码,发现,replace()这个方法只是在上一个Fragment不再需要时采用的简便方法。

    正确的切换方式是add(),切换时hide(),add()另一个Fragment;再次切换时,只需hide()当前,show()另一个。
    这样就能做到多个Fragment切换不重新实例化:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
        public void switchContent(Fragment from, Fragment to) {
            if (mContent != to) {
                mContent = to;
                FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(
                        android.R.anim.fade_in, R.anim.slide_out);
                if (!to.isAdded()) {    // 先判断是否被add过
                    transaction.hide(from).add(R.id.content_frame, to).commit(); // 隐藏当前的fragment,add下一个到Activity中
                } else {
                    transaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个
                }
            }
        }
    

    摘自:http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/

  • 相关阅读:
    结对练习(能力有限,待解决......)
    骰子修改
    骰子传奇
    现在的辛苦一点,会是将来的更好一点!
    入坑?那就从坑里爬出来
    性能测试工具locust简单应用
    阿里云环境部署
    Charles的安装与抓取手机包设置
    windows常用命令-netstat
    采坑小记——adb链接夜神模拟器
  • 原文地址:https://www.cnblogs.com/veins/p/4137834.html
Copyright © 2011-2022 走看看