I've been trying to figure this one out.
I'll start by saying that there are many StackOverflow solutions but most say to hookup the onBackPressed() myself, which does work, but I don't understand why I don't get that behavior for free with the .addToBackStack
Can't find anything relevant in the documentation except that it should have worked.
I am using the simplest of forms to add a fragment to the backstack
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.create_fragment_holder2, new MyFragment(), TAG).addToBackStack(TAG).commit();
getActivity is a FragmentActivity. Goes along with this FrameLayout:
<FrameLayout
android:id="@+id/create_card_fragment_holder2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And a simple fragment with a TextView with a blue background
public class MyFragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_layout, container, false);
}}
Problem is that if I don't ask .addToBackStack then the back button will close the containing fragment, and if I do, the back button is non responsive and I will forever see that blue screen.
Every StackOverflow solution I found says to hookup the onBackPressed() myself, which does work, but I don't understand why I don't get that behavior for free with the .addToBackStack Can't find anything relevant in the documentation except that it should have worked.
UPDATE: I found out it was not working because I was blocking it in the onBackPress in the activity. So without it it will work as expected. That said it's a good place to enter validation and prevent it from working, should that be your need :)