zoukankan      html  css  js  c++  java
  • Android开发之Fragment的替换显示反复创建问题

    一般写程序时我们都是得到FragmentManager,然后开启一个事务,然后进行Fragment的替换,然后提交事务。

    //1.得到FragmentManger
            FragmentManager fm = getSupportFragmentManager();
    //        //2.开启事务
            FragmentTransaction transaction = fm.beginTransaction();
    //        //3.替换
            transaction.replace(R.id.fl_content, fragment);
    //        //4.提交事务
            transaction.commit();

    但是,在实际的开发中,这种方式会导致Fragment的频繁创建,消耗用户的流量,所有提出以下优化:

    就是用Add()和Hide() ,讲之前的Fragment隐藏,然后把要显示的Fragment添加进去,当要显示之前那个Fragment的时候,直接show()出来就可以了。

    private void switchFrament(Fragment from,Fragment to) {
            if(from != to){
                mContent = to;
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                //才切换
                //判断有没有被添加
                if(!to.isAdded()){
                    //to没有被添加
                    //from隐藏
                    if(from != null){
                        ft.hide(from);
                    }
                    //添加to
                    if(to != null){
                        ft.add(R.id.fl_content,to).commit();
                    }
                }else{
                    //to已经被添加
                    // from隐藏
                    if(from != null){
                        ft.hide(from);
                    }
                    //显示to
                    if(to != null){
                        ft.show(to).commit();
                    }
                }
            }
    
        }

    提示:记得在add()  Fragment的时候判断是否为null.

    GitHub:https://github.com/godfunc
    博客园:http://www.cnblogs.com/godfunc
    Copyright ©2019 Godfunc
  • 相关阅读:
    git上传
    #if debug 模式
    .net core 获取appsetting配置信息
    映射的问题
    net core 支付宝回调参考
    .net core 3.1开发遇到的问题
    .net core 中对象转json以及反序列化
    auotmapper在net core 3.1的使用
    net core 3.1 webapi的开发遇到的问题
    OCP prepare 20140703
  • 原文地址:https://www.cnblogs.com/Godfunc/p/6433373.html
Copyright © 2011-2022 走看看