1

I have fragments in backstack which is added by using addtobackstack function. When i add a fragment without not using addtobackstack function and then press back button, the backstack is go back to wrong fragment.

For example:

Fragment A is replaced by using addtobackstack

Fragment B is replaced by using addtobackstack

Fragment C is replaced without not using addtobackstack

Fragment D is replaced by using addtobackstack

When i was in Fragment D and press the back button, i am going to Fragment A. But i must go to Fragment B.

How can i fix it?

Thanks,

aligur
  • 3,387
  • 3
  • 34
  • 51

1 Answers1

1

Put this code in Activity then try.

Fragment is followed with Activity so when you use fragment with addToBackStack() with tag or passing null will add fragment in stack with help of FragmentManager.

Not necessary to addToBackStack(). comment this code or pass null

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction();
    fragmentTransaction .replace(R.id.fragment_container, YouNextFragment);
    fragmentTransaction .addToBackStack(null);
    fragmentTransaction .commit();

When you press back button in Activity FragmentManager automatically popUp latest added fragment.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case android.R.id.home:                  
                if (getFragmentManager().getBackStackEntryCount() ==0) {
                    finish();
                }else{
                    getFragmentManager().popBackStack();
                }
                break;

            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }
Ajinkya
  • 1,029
  • 7
  • 15
  • can you please explain how this code will help to achieve what is asked in the question? – Ankit Aggarwal Feb 19 '16 at 13:22
  • i think this answer not about what i asked :) but i will try. I dont want to add specific fragment to backstack. But you said that add all fragments to backstack with "null" parameter. – aligur Feb 19 '16 at 13:34