0

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();
    }
}
Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40
maryam
  • 1,437
  • 2
  • 18
  • 40

2 Answers2

1

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.

Adil Iqbal
  • 142
  • 3
  • 12
  • I add Fragment to `addToBackStack` and return to my Activity. But my app show blank activity! – maryam Sep 16 '18 at 08:05
  • Can you show how you are creating and adding the fragment? May be you're using `SupportFragmentManager` for adding the fragment and `FragmentManager` is returning count 0. – Adil Iqbal Sep 16 '18 at 08:13
1

As I understand all you want to do is when users press Back key on MainActivity

  • If there are more than 1 fragments in the back stack just pop out the fragment
  • If there is only 1 fragment in the back stack, first back press will be ignored and you would like to run some additional code. Then if users press back key again, your 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()
    }
}
Son Truong
  • 13,661
  • 5
  • 32
  • 58