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

后端 未结 10 1849
孤独总比滥情好
孤独总比滥情好 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 00:47

    Just find the current fragment calling getFragmentById("id of your container") and then hide it and show needed fragment.

    private void openFragment(Fragment fragment, String tag) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment existingFragment = fragmentManager.findFragmentByTag(tag);
            if (existingFragment != null) {
                Fragment currentFragment = fragmentManager.findFragmentById(R.id.container);
                fragmentTransaction.hide(currentFragment);
                fragmentTransaction.show(existingFragment);
            }
            else {
                fragmentTransaction.add(R.id.container, fragment, tag);
            }
            fragmentTransaction.commit();
        }
    

提交回复
热议问题