I'm using the Android Compatibility library to implement fragments and have extended the layout sample so that a fragment contains a button which fires off another fragment.
In the selection pane on the left I have 5 selectable items - A B C D E
.
Each loads up a fragment (via FragmentTransaction:replace
) in the details pane - a b c d e
Now I've extended fragment e
to contain a button which loads up another fragment e1
also in the details pane. I've done this on fragment e
's onClick method as follows:
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details_frag, newFrag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
If I make the following selections:
E - e - e1 - D - E
Then fragment e
is in the details pane. This is fine and what I want. However, if I hit the back
button at this point it does nothing. I have to click it twice because e1
is still on the stack. Furthermore after clicking around I got a null pointer exception in onCreateView:
To 'solve' this problem I added the following whenever A B C D E
is selected:
FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
Just wondering whether this is the correct solution or whether I should be doing something different?