Reputation: 23952
How to remove current and show previous fragment? Like if I'm press "Back" button
I'm using such construction:
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();
But it just removes current fragment, without showing previous
Upvotes: 7
Views: 9036
Reputation: 6357
Add this method in 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 where you are changing the fragments do this:
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();
Upvotes: 4
Reputation: 333
Try to show previous fragment after remove:
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();
previousFragment=(SherlockFragment)getSupportFragmentManager()
.findFragmentByTag(""+currentTagNum);
getSupportFragmentManager().beginTransaction()
.show(mFragment)
.commit();
Upvotes: 0
Reputation: 739
You have to call FragmentTransaction.addToBackStack(null)
where you add the fragment and then call FragmentManager.popBackStack()
when you want to remove it.
Upvotes: 13