0

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();
            fragmentManager.beginTransaction()
                    .add(R.id.main_container, fragment)
                    .addToBackStack("fragBack")
                    .commit();
        } 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?

Thanks!

Rob
  • 1,162
  • 2
  • 18
  • 43
  • i think this link will same as your question.. http://stackoverflow.com/questions/18755550/fragment-pressing-back-button – Ranjit Apr 29 '14 at 19:11

1 Answers1

0

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.

BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84