Android - Simulate a back button

When I click the button in my application, I need to go back to the last action.

Any ideas?

+62
android button back
Apr 27 '10 at 0:29
source share
5 answers

Calling finish() from the action you want to complete should take care of this.

Edit many years later:. This still works, but it is a bit complicated approach. When I originally posted this, Fragments did not exist, and (as several commentators have pointed out) this does not work completely wrong when there are Fragments . Now there are better approaches if you use Fragments.

+89
Apr 27 2018-10-12T00:
source share

For write only: the described method does not do the same as in the previous button, but you can call

 this.onBackPressed(); 

or

 getActivity().onBackPressed(); 

if you are in a fragment to achieve the same behavior.

+49
Apr 15 '14 at 12:33
source share

when using fragments:

 getFragmentManager().popBackStack(); 

or

 getSupportFragmentManager().popBackStack(); 

if you use the android.support.v4.app package

+33
May 09 '13 at 19:07
source share

This is for a situation where the same fragment can sometimes be the only fragment in the activity, and sometimes part of multiple activity, for example, on a tablet, where two fragments are displayed simultaneously.

 /** * 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-ie-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 the Cancel button, for example.

  if (theButton.getId() == R.id.btnStatusCancel) { StaticMethods.fragmentImplementCancel(this); } 
+1
Feb 03 '14 at 11:23
source share

You can replace the up button on the back button:

 @Override public void onBackPressed() { onNavigateUp(); } 
0
Nov 23 '14 at 19:48
source share



All Articles