Switching between fragments programmatically

I want to switch between 2 fragments located in 1 activity, so the other fragment should always replace the current one. I cannot find my error :(

My main activity:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);

    Fragment fragment = new FirstFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment, "first");
    transaction.addToBackStack(null);
    transaction.commit();
}

      

My activity_layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />

      

Now, at some point in the FirstFragment logic (which works great), the following method is called

    private void startSecondFragment(){

    Fragment fragment = new SecondFragment();
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment, "second");
    transaction.addToBackStack(null);
    transaction.commit();

}

      

This function completes without error, but the following exception is immediately thrown:

02-11 13:40:30.533: E/AndroidRuntime(907): java.lang.IllegalArgumentException: No view found for id 0x7f070000 (com.myexample.app:id/container) for fragment SecondFragment{412c9388 #0 id=0x7f070000 second}

      

Now it seems that it was unable to find the identifier "container" at this point (the first snippet replaced this container). How can I replace the first snippet?

+3


source to share


1 answer


It should be like this:

private void startSecondFragment(){

    Fragment fragment = new SecondFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment, "second");
    transaction.addToBackStack(null);
    transaction.commit();

}

      



You don't want to get a child FragmentManager because your Fragments are in your Activity, so you need the exact same Fragment Manager.

+3


source







All Articles