Pressing the back button after the Snippet transaction using addToBackStack does nothing

I want to be able to undo replace FragmentTransaction with addToBackStack() :

 FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction(); Fragment scheduleFragment = new ScheduleFragment(); fragmentTransaction.replace(R.id.content_container, scheduleFragment, "scheduleFragment"); fragmentTransaction.addToBackStack("scheduleFragment"); fragmentTransaction.commit(); 

but after that, pressing the back button does nothing.

From the document and he must cancel the transaction.

What am I missing?

+6
source share
4 answers

The right way to do this is to use the onBackPressed() method to catch this event in your application, and then pop the backStack using popBackStack() . For instance:

 public void onBackPressed() { // Catch back action and pops from backstack // (if you called previously to addToBackStack() in your transaction) if (getSupportFragmentManager().getBackStackEntryCount() > 0){ getSupportFragmentManager().popBackStack(); } // Default action on back pressed else super.onBackPressed(); } 

PD: Sorry for the delay in answering, but I just saw your question. Hope this helps!

+24
source

Try fragmentTransaction.addToBackStack(null) The parameter for addToBackStack() is an optional name for the back state, you do not use the tag in the replace() method, which is just an optional tag for the fragment. You can read about it here .

+4
source

I was not for long, but I hope this helps someone.

fragmentTransaction.addToBackStack(null) will not work if you extend AppCompatActivity . It works well in Activity . I could not find the reason.

+2
source

I implemented my own Fragment stack:

 public Fragment addFragmentToStack(Fragment fragment){ if(MyApplication.fragmentStack.size()>20){ MyApplication.fragmentStack.remove(0); } return MyApplication.fragmentStack.push(fragment); } public void onBackPressed() { if (MyApplication.fragmentStack.size() > 0) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_container, MyApplication.fragmentStack.pop()); ft.commit(); } else{ finish(); } } 
0
source

Source: https://habr.com/ru/post/951990/


All Articles