Rob Rob - 1 year ago 84
Android Question

Handling Back Button with Fragment

In my MainActivity, I am launching a fragment using the following:

private void displayView() {
Log.d("displayView", "in select item");
// update the main content by replacing fragments
Fragment fragment = null;
fragment = new WorkoutsFragment();

if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
.add(, fragment)
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");

This loads my fragment correctly, and I am able to see it, however, when I hit the back button it exits the application. I would like it to go back to MainActivity if possible.

Is this improper handling of a fragment? If so, what would be the correct way of approaching this?


Answer Source

You can override onBackPressed in your main activity and not call super.onBackPressed. In the overriden method, you can remove the fragment from the fragment manager.