maryam
maryam

Reputation: 1505

Handle `BackPressed` when we only have a fragment

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

Answers (2)

Son Truong
Son Truong

Reputation: 14173

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()
    }
}

Upvotes: 1

Adil Iqbal
Adil Iqbal

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

Related Questions