Lee Wang Lee Wang - 15 days ago 5
Android Question

Programatically switching between Fragments

I want to switch between 2 Fragments located in 1 activity, so the other fragment should always replace the current one. I can´t find my error though :(

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 within the logic of the FirstFragment (which works fine), the following method is being 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 does finish without an error, however right afterwards the following exception is getting 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 like its not able to find the id "container" at this point (the first Fragment has replaced this container). How can I really replace the first fragment??

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 child's FragmentManager, because your fragments are in your Activity, so you need the same fragmentManager.