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
2 Answers. Show activity on this post. and when you click on back button in the toolbar programmatically go back to the previous fragment using following code.
Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container.
A Fragment represents a behavior or a portion of user interface in an Activity . You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
You have to call FragmentTransaction.addToBackStack(null)
where you add the fragment and then call FragmentManager.popBackStack()
when you want to remove it.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With