I am developing application in which I have three fragment A,B,C, when I press on some button in A it navigate to b Thats fine ,and when I press device back button application closes instead of going to A,How can I prevent this problem .
Asked
Active
Viewed 1,389 times
2
-
1Possible duplicate of [Android Overriding onBackPressed()](http://stackoverflow.com/questions/18337536/android-overriding-onbackpressed) – Bö macht Blau Feb 12 '16 at 07:26
-
Because clicking "Back" button triggers your holder activity to close rather move back to fragment. To handle fragments implement backstack mechanism using fragment's life cycle. – gauravsheohar Feb 12 '16 at 07:28
-
Possible duplicate of [Programmatically go back to the previous fragment in the backstack](http://stackoverflow.com/questions/10863572/programmatically-go-back-to-the-previous-fragment-in-the-backstack) – Dr.jacky Feb 12 '16 at 07:41
4 Answers
2
// Your Main Activity // Override OnBackPressed Event Which as below
@Override
public void onBackPressed() {
if (getSupportFragmentManager()
.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else {
UIUtils.showAlertDialog(this, getString(R.string.app_name), "Are you sure want to Exit App?", false);
}
}

jigspatel
- 400
- 3
- 14
0
You should override onBackPressed() method. There you can choose what action to do when this happens. If you still want to finish the activity in some cases, you can call finish() method.

Camilo Ortegón
- 3,414
- 3
- 26
- 34
0
Please add
addToBackStack(null);
to your FragmentTransaction object if you not added when replacing or adding fragments.
it will autamatically maintain backstacks on Backpress.
Hope it will help you !

Rahul
- 510
- 3
- 8