重用弹出的片段

时间:2017-04-20 11:35:09

标签: android android-fragments

让我们看看这张照片:

fragmentA->FragmentB

在Android教程中,每次FragmentA替换为FragmentB时,都会创建FragmentB的新实例。

让我们查看下一个案例FragmentAFragmentB然后返回(按)至FragmentA并再次转至FragmentB。也许如果FragmentB的旧实例仍然活着会更好地使用它(只更新数据)而不是创建新实例?有没有简单的方法呢?

2 个答案:

答案 0 :(得分:0)

尝试使用fragmentTransaction.show方法重用现有片段。

使用以下方法切换片段,如果已经添加了片段,它将显示片段。

public void switchFragment (Fragment oldFragment, Fragment newFragment, int frameId) {

    boolean addFragment = true;

    FragmentManager fragmentManager = getFragmentManager ();
    String tag = newFragment.getArguments ().getString (BaseFragment.TAG);
    Fragment fragment = fragmentManager.findFragmentByTag (tag);

    // Check if fragment is already added
    if (fragment != null && fragment.isAdded ()) {
        addFragment = false;
    }

    // Hide previous fragment
    String oldFragmentTag = oldFragment.getArguments ().getString (BaseFragment.TAG);

    if (!tag.equals (oldFragmentTag)) {
        FragmentTransaction hideTransaction = fragmentManager.beginTransaction ();
        Fragment fragment1 = fragmentManager.findFragmentByTag (oldFragmentTag);
        hideTransaction.hide (fragment1);
        hideTransaction.commit ();
    }

    // Add new fragment and show it
    FragmentTransaction addTransaction = fragmentManager.beginTransaction ();

    if (addFragment) {
        addTransaction.add (frameId, newFragment, tag);
        addTransaction.addToBackStack (tag);
    }
    else {
        newFragment = fragmentManager.findFragmentByTag (tag);
    }

    addTransaction.show (newFragment);

    addTransaction.commit ();
}

答案 1 :(得分:0)

您可以为片段使用简单的Singleton,

public class FragmentGoogleMap extends Fragment implements OnMapReadyCallback {

MapView mapView;
GoogleMap googleMap;

private static FragmentGoogleMap instance = null;

private FragmentGoogleMap() {
}

public static FragmentGoogleMap getInstance(){
    if(instance == null){
        instance = new FragmentGoogleMap();
    }
    return instance;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

frome活动你可以获得实例

private FragmentGoogleMap fragmentGoogleMap;
private FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fragmentManager = getSupportFragmentManager();
    fragmentGoogleMap = FragmentGoogleMap.getInstance();
    fragmentManager.beginTransaction().replace(R.id.fragment_map_container,fragmentGoogleMap).commit();

}