How can I switch between two fragments, without recreating the fragments each time?

后端 未结 10 1894
孤独总比滥情好
孤独总比滥情好 2020-12-08 00:19

I\'m working on an android application, that uses a navigation drawer to switch between two fragments. However, each time I switch, the fragment is completely recreated.

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 01:11

    Use the attach/detach method with tags:

    Detach will destroy the view hirachy but keeps the state, like if on the backstack; this will let the "not-visible" fragment have a smaller memory footprint. But mind you that you need to correctly implement the fragment lifecycle (which you should do in the first place)

    Detach the given fragment from the UI. This is the same state as when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.

    The first time you add the fragment

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.add(android.R.id.content, new MyFragment(),MyFragment.class.getSimpleName());
    t.commit();
    

    then you detach it

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.detach(MyFragment.class.getSimpleName());
    t.commit();
    

    and attach it again if switched back, state will be kept

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.attach(getSupportFragmentManager().findFragmentByTag(MyFragment.class.getSimpleName()));
    t.commit();
    

    But you always have to check if the fragment was added yet, if not then add it, else just attach it:

    if (getSupportFragmentManager().findFragmentByTag(MyFragment.class.getSimpleName()) == null) {
        FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.add(android.R.id.content, new MyFragment(), MyFragment.class.getSimpleName());
        t.commit();
    } else {
        FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.attach(getSupportFragmentManager().findFragmentByTag(MyFragment.class.getSimpleName()));
        t.commit();
    }
    

提交回复
热议问题