Reputation: 1505
I have an Activity
and it has only one Fragment
. I want to handle backpressed
functionality. When user presses back, program should go back to Activity
. I know this is very simple but I have tried some solutions that are mentioned on Stackoverflow, but none of them worked. For example I tried this:
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
Upvotes: 0
Views: 53
Reputation: 14173
As I understand all you want to do is when users press Back key on MainActivity
MainActivity
will be finished.Change your code to
private boolean ignoredFirstBackPressed = false;
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 1) {
// If there is only one fragment in back stack
if (!ignoredFirstBackPressed) {
// additional code
ignoredFirstBackPressed = true;
} else {
finish();
}
} else {
getFragmentManager().popBackStack(); // or super.onBackPressed()
}
}
Upvotes: 1
Reputation: 152
Your code seems to be correct. Did you add Fragment
to backstack using addToBackStack
? Have a look at this question. It's similar to yours.
Upvotes: 1