欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > 内容正文

Android,androidsdk

来源: 开发者 投稿于  被查看 41340 次 评论:226

Android,androidsdk


问题:
在项目中需要进行Fragment的切换,可以使用replace()方法来替换Fragment:

    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切换不重新实例化:

    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,显示下一个
            }
        }
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关频道:

用户评论