---
title: "Android  让多个Fragment 切换时不重新实例化"
author: "zhouxiaoli521"
date: "2013-12-05T18:48:23Z"
tags: []
categories: ["移动开发"]
slug: "android-fragment"
draft: false
lastmod: "2013-12-05T18:48:23Z"
id: 1985815
url: "https://mycoding.iteye.com/blog/1985815"
---

在项目中需要进行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，显示下一个
            }
        }
    }
```

 

[http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/#](http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/)