Android - Simulate Back Button

AndroidButtonBack

Android Problem Overview


When i press a button in my app, I need to return to the last activity.

Any ideas?

Android Solutions


Solution 1 - Android

Calling finish() from the activity you want to end should take care of this.

Edit many years later: This still works, but it's a bit of a heavy-handed approach. When I originally posted this, Fragments didn't exist, and (as several commenters have pointed out) this doesn't work quite the same way when there are Fragments involved. There are better approaches now if you're using Fragments.

Solution 2 - Android

Just for record: The described method doesn't do the same as the back button does in some cases, but you can call

this.onBackPressed();

or

getActivity().onBackPressed();

if you are in a fragment to achieve exaclty the same behaviour.

Solution 3 - Android

when using fragments:

getFragmentManager().popBackStack();

or

getSupportFragmentManager().popBackStack();

if you are using android.support.v4.app package

Solution 4 - Android

This is for a situation where the same fragment may sometimes be the only fragment in an activity, and sometimes part of a multi-fragment activity, for example on a tablet where two fragments are visible at the same time.

/**
 * Method that can be used by a fragment that has been started by MainFragment to terminate
 * itself. There is some controversy as to whether a fragment should remove itself from the back
 * stack, or if that is a violation of the Android design specs for fragments. See here:
 * http://stackoverflow.com/questions/5901298/how-to-get-a-fragment-to-remove-itself-i-e-its-equivalent-of-finish
 */
public static void fragmentImplementCancel(Fragment fragment) {

    FragmentActivity fragmentActivity = fragment.getActivity();
    FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();

    if (fragmentManager.getBackStackEntryCount() == 1) {
        fragmentManager.popBackStack();
    }
    else {
        fragmentActivity.finish();
    }
}

This code can be called to implement a Cancel button, for example.

    if (theButton.getId() == R.id.btnStatusCancel) {
        StaticMethods.fragmentImplementCancel(this);
    }

Solution 5 - Android

You can spoof a up button call on back button press:

@Override
public void onBackPressed() {
    onNavigateUp();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondavidView Question on Stackoverflow
Solution 1 - AndroidChris ThompsonView Answer on Stackoverflow
Solution 2 - Android黄雨伞View Answer on Stackoverflow
Solution 3 - Androidzajac.m2View Answer on Stackoverflow
Solution 4 - AndroidRenniePetView Answer on Stackoverflow
Solution 5 - AndroidshanikView Answer on Stackoverflow