1

I have fragmentA on my backstack and fragmentB on the screen. I want to replace fragmentB with fragmentC so that when user pressed back, we go back to fragmentA. This is how I am replacing fragmentB with fragmentC

    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content_container, fragment);
    transaction.commitAllowingStateLoss();

This is how I'm handling back press

    final FragmentManager fm = getSupportFragmentManager();
    if (fm.getBackStackEntryCount() != 0) {
        fm.popBackStackImmediate();
    } else {
        super.onBackPressed();
    }

After replacing fragmentB with fragmentC, when back button pressed fragmentA will be shown, but fragmentC is still visible on the screen, which is giving me some really weird UI. Anyone know why this is happening??

azizbekian
  • 60,783
  • 13
  • 169
  • 249
Marc Li
  • 11
  • 4
  • can show us the complete code ,, where you are assigning value to 'fragment' and all. and are you using fragments with tabbed view or drawer view ? – Zainab Jamil Mar 09 '18 at 06:41

2 Answers2

0

Add the transaction to the backstack:


    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content_container, fragment);
    transaction.addToBackStack("")
    transaction.commitAllowingStateLoss();

azizbekian
  • 60,783
  • 13
  • 169
  • 249
0

If i get you correctly, FragmentA is overlayed on FragmentC hence both fragments are visible.

If this is the case, set the background of both fragments A and C in the xml layout. Here is an example

FragmentA

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tool="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="#FFF"
     android:orientation="vertical">

    //Fragment A contents

</LinearLayout>

FragmentC

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tool="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="#FFF"
     android:orientation="vertical">

     //Fragment C contents

  </LinearLayout>

Observe that both fragments have the background attribute set in their rootview. So though they are overlayed, only one is visible at a time.

Akinola Olayinka
  • 841
  • 7
  • 11