Show previous snippet

How to delete the current and show the previous fragment? For example, if I click the back button

I use this construct:

FragmentManager fm=getFragmentManager(); FragmentTransaction ft=fm.beginTransaction(); ft.remove(fragment).commit(); 

But it just deletes the current fragment without showing the previous ones

+7
source share
3 answers

You need to call FragmentTransaction.addToBackStack(null) where you add the fragment, and then call FragmentManager.popBackStack() when you want to delete it.

+13
source

Add this method to your activity:

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if( this.getFragmentManager().getBackStackEntryCount() != 0 ){ this.getFragmentManager().popBackStack(); return true; } // If there are no fragments on stack perform the original back button event } return super.onKeyDown(keyCode, event); } 

Then, when you change the fragments, do the following:

 FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(android.R.id.content, new YourFragmentName()); transaction.addToBackStack(null); // this is needed for the above code to work transaction.commit(); 
+4
source

Try to show the previous fragment after deletion:

  FragmentManager fm=getSupportFragmentManager(); FragmentTransaction ft=fm.beginTransaction(); ft.remove(fragment).commit(); previousFragment=(SherlockFragment)getSupportFragmentManager() .findFragmentByTag(""+currentTagNum); getSupportFragmentManager().beginTransaction() .show(mFragment) .commit(); 
0
source

All Articles