Skip to content Skip to sidebar Skip to footer

Fragments Addtobackstack Closing The Application

I am calling some fragments from HomeScreen.java. Now whenever i press back button in any fragment, its closes the application. But i want previous fragment which was loaded.Follow

Solution 1:

Suppose you have 3 fragments

(1) Fragment A

(2) Fragment B

(3) Fragment C

You are going A to B then B to C then Backpress will return to B then again Backpress will return to A then Backpress will close app.

Method for replace Fragment by adding Tag:

Pass your fragment and tag as arguments in below method.

privatevoidreplaceFragment(Fragment frag, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.realtabcontent, frag);
    transaction.addToBackStack(tag);
    transaction.commitAllowingStateLoss();
}

No need to write onBackPress() or fragmentManager.popBackStack(), it will automatically handle.

Done

Solution 2:

Add this

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

Post a Comment for "Fragments Addtobackstack Closing The Application"