I have multiple fragments.I want to save all Instances in backstack till the home button pressed again

81 Views Asked by At

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

There are 1 best solutions below

1
Mohammad Reza Ghariblu On

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