Skip to content Skip to sidebar Skip to footer

Programmatically 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: @Ove

Solution 1:

It should be like this:

privatevoidstartSecondFragment(){

    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.

Post a Comment for "Programmatically Switching Between Fragments"