Fragment A calls fragment B - B does a popbackstack - where does it return in A

482 views Asked by At

I cant' find where it returns in Fragment A after a call to fragment B.

Fragment A calls fragment Test as follows:

btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                FragmentTransaction ft = getFragmentManager().beginTransaction();
Test test = new Test();
                ft.replace(R.id.container, test);
                ft.addToBackStack("test");
                ft.commit();
            }
        });

In Test I click on a button to return:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Button btn = (Button) getActivity().findViewById(R.id.back);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getActivity().getFragmentManager().popBackStackImmediate();
        }
    });
}

From there I thought that it was returning to Fragment A in onAttach, onResume but I don't see where it is returning in Fragment A?

   @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
2

There are 2 answers

7
Sharath kumar On

PopBackStack() doesn't pop a fragment, it pops a fragment transaction.

So the last fragment transaction is reversed upon being called. If you are moving from FragmentA to FragmentTest then it would replace FragmentA with FragmentTest and add that transaction to the back stack(not the fragment). If you then hit the back button, it pops the transaction off the back stack, which was "replace this FragmentA with a FragmentTest".

This instruction reverses the last transaction and removes it from the stack of transactions carried out. So onAttach wont be called and since your are replacing the fragment oncreateView will be called.

Edit:Use this function to check backstack is present and has your test fragment.

if (getSupportFragmentManager().getBackStackEntryCount() > 0 && getSupportFragmentManager().findFragmentById(R.id.your_container)!=null) {
     Fragment fragment= getSupportFragmentManager().findFragmentById(R.id.your_container);
      if(fragment.getClass().getSimpleName().equalsIgnoreCase(FragmentTest.class.getSimpleName())){
          getSupportFragmentManager().popBackStackImmediate();
        }
    }
3
Tavinder Singh On

Use

Log.d("Fragment", "Fragment A")

in onResume() method of Fragment A class. If control returns to Fragment A then this line will be shown in logcat.