Load Fragment in Activity OnCreate

Viewed 23495

Problem: Switching from fragment 1 to fragment 2, the switch happens, but both are visible. (fragment 2 comes into focus)

Fragment 1 is MenuFragment Fragment 2 is GameFragment

I believe this is happening because my fragment 1 is included in my main activity.xml

   <fragment
        android:id="@+id/menu_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_menu">
    </fragment>

The code above in main.xml loads the fragment into the main activity. Whenever I replace the menu fragment with game fragment using this code:

public void replaceFragment(Fragment fragment) 
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.gameview_layout, gameFragment);
    fragmentTransaction.addToBackStack(fragment.toString());
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fragmentTransaction.commit();
}

the game fragment appears and overlays above the menu fragment. How do I get the menu fragment to disappear? I'm sure an easy fix would be makeVisible(false) or something similar, but I believe the real problem is programming in the xml file to include the MenuFragment in the first place.

Question: How do I program in the main.java class to load a fragment on create?

I want to do this, so I can program it to load fragment 1 (MenuFragment) first without it already being there. The only reason both are visible is because fragment 1 is included in my main.xml

3 Answers
Related