Search code examples
androidandroid-fragmentsfragmentandroid-fragmentactivityfragmentmanager

Fragment replacement shows the two fragments


I try to replace a fragment in my main layout.

In my main layout I have :

<fragment
        android:id="@+id/frame_informations"
        android:name="GridFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="2dp"
        android:layout_marginEnd="2dp"
        app:layout_constraintBottom_toTopOf="@+id/main_bottom_menu"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/llLit"/>

When I want to replace this fragment, I use :

 public void switchFrameInformations(Fragment newFragment) {
            try {

                FragmentTransaction ft = fm.beginTransaction();
               // ft.setCustomAnimations(android.R.anim., android.R.anim.fade_out);
                if (fm.findFragmentById(R.id.frame_informations) == null) {
                    ft.add(R.id.frame_informations, newFragment);
                } else {
                    ft.replace(R.id.frame_informations, newFragment);
                }
              //  ft.addToBackStack(null);
                ft.commit();
                fm.findFragmentById(R.id.frame_informations).getView().requestLayout();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

fm is the Fragment Manager...

This works, but something strange happens : the new fragment contains a list of name, and the background is transparent. At the end of the replacement, I can see the old fragment in the background of the new one...

In the debug console, I can see that all the methods are normally called : onDestroy etc...for the old fragment. I guessed that the name in the XML description could cause a problem :

android:name="GridFragment"

But I can not compile if there is no name...

As far as I think this is a common problem, I tried to find a solution on the Web, but I could not find any solution.

Thank you for your help.


Solution

  • Replace <fragment with <FrameLayout The in your activity in onCreate add the following code

    if (savedInstanceState == null) {
        fm.beginTransaction()
            .replace(R.id.frame_informations, GridFragment())
            .commit();
    }
    

    This will initialize your fragment correctly and allow you to switch fragments easily in code.