Fragment re-created on bottom navigation view item selected Solution

21-01-2019
private void changeFragmentForBottomNavigationView(Bundle savedInstanceState, Fragment fragment) {
    
    if (findViewById(R.id.fragment_container) != null) {
        
        if (savedInstanceState != null) {
            return;
        }
        
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        
        Fragment curFrag =getSupportFragmentManager().getPrimaryNavigationFragment();
        if (curFrag != null) {
            fragmentTransaction.detach(curFrag);
        }
        
        Fragment fragmentFromManager = getSupportFragmentManager()
        .findFragmentByTag("BOTTOM_FRAGMENT_"+fragment.getClass().getName());
        if (fragmentFromManager == null) {
            fragmentFromManager = fragment;
            fragmentTransaction.add(R.id.fragment_container, fragmentFromManager,
            "BOTTOM_FRAGMENT_"+fragment.getClass().getName());
        } else {
            fragmentTransaction.attach(fragmentFromManager);
        }
        
        fragmentTransaction.setPrimaryNavigationFragment(fragmentFromManager);
        fragmentTransaction.setReorderingAllowed(true);
        fragmentTransaction.commitNowAllowingStateLoss();
    }
}

© 2019 All rights reserved. Codesenior.COM