Gaetan L.
Gaetan L.

Reputation: 665

Android back button and fragment activity

I have an activity which uses fragments, when the activity is first created, it displays a first fragment which is not added to back stack cause I don't want to have an empty activity when user presses back.

The fragments loaded after that are added to back stack.

So I have the behavior I want, except: user can open fragments and press back to go back to the previous fragment, up until they reach the first fragment because if they press back at this time, the activity is closed, which I don't want.

So I'd like to know a good solution to prevent back button pressed but only when the first fragment is displayed.

Upvotes: 0

Views: 1369

Answers (3)

Ankita
Ankita

Reputation: 1149

Add .addToBackStack(null) when you call the new fragment from activity.

FragmentTransaction mFragmentTransaction = getFragmentManager()
                    .beginTransaction();
        ....
        mFragmentTransaction.addToBackStack(null);

-Add onBackPressed() to your activity

   @Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() == 0) {
        this.finish();
    } 
else {
        getFragmentManager().popBackStack();
    }
}

Upvotes: 4

Dhiren Basra
Dhiren Basra

Reputation: 860

in your activity class add below code in onBackPressed method;

@Override
public void onBackPressed() {
int backstack = getSupportFragmentManager().getBackStackEntryCount();

 if (backstack > 0) {
     getSupportFragmentManager().popBackStack();
 }
  else{
      super.onBackPressed();
      //System.exit(0);
  }
}

hope this help.

Upvotes: 2

Gaetan L.
Gaetan L.

Reputation: 665

Solved like this:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount()> 0) {
        super.onBackPressed();
    }
}

Upvotes: 2

Related Questions