码迷,mamicode.com
首页 > 移动开发 > 详细

Android开发之Fragment的替换显示

时间:2017-02-23 15:48:35      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:gets   hid   com   方式   ide   显示   support   int   pre   

一般写程序时我们都是得到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.

Android开发之Fragment的替换显示

标签:gets   hid   com   方式   ide   显示   support   int   pre   

原文地址:http://www.cnblogs.com/Coderwei2016/p/6433373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!