0

I tried many methods to save instances but I am confused how to save instances in backstack because no one described how to use it if there multiple fragments.my code in mainactivity below:

bottomNavigationView.setOnItemSelectedListener(item -> {
    switch (item.getItemId()){
            case R.id.home:
                loadFragment(new HomeFragment(),0);
                break;

        case R.id.create:

      loadFragment(new CreateFragment(),1);
            break;

        case R.id.profile:
            loadFragment(new ProfileFragment(),1);
            break;
    }
    return true;
});
    public void loadFragment(Fragment fragment,int flag){
        FragmentManager fragmentManager=getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        if(flag==0){
            fragmentTransaction.add(R.id.frame_layout,fragment);
            fragmentManager.popBackStack(ROOT_FRAGMENT_TAG,FragmentManager.POP_BACK_STACK_INCLUSIVE);
                fragmentTransaction.addToBackStack(ROOT_FRAGMENT_TAG);
        }
        else {
            fragmentTransaction.replace(R.id.frame_layout,fragment);
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }

1 Answers1

0

I suggest you to make your Fragment Classes Singleton.

private static MyFragment fragment;


public static MyFragment getInstance() {
    if (fragment == null) {
        fragment = new MyFragment();
    }
    return fragment;
}

then use getInstance() method to instantiate your fragment

  • 1
    30 Fragments are meant to be reusable components of applications. You should not be using them as singletons, instead you should implement Fragment.SavedState or onSavedInstanceState. – Aparichit_Coder Jun 22 '22 at 15:02