Skip to content Skip to sidebar Skip to footer

Fragment Replacing Existing Fragment

I have the MainActivity, it contains ListFragment and framelayout, I am able to change the fragments on list on item click. I have a problem to replace the existing Fragment1 with

Solution 1:

You need to use .replace to switch the two fragments, you also need add add the original to the backstack so you can recall it, and you need to override the back key operation to function that way. It would look something like this (using code from one of my projects, using the support library):

To show your first fragment:

menu = newMenuFragment_Main();   // instantiate fragmentgetSupportFragmentManager().beginTransaction().replace(R.id.pane, menu).commit();  // display fragment

To swap it for the new fragment and add it to the backstack:

ListFragment_ShopListItemshoplist=newListFragment_ShopListItem();  // instantiate fragment
getSupportFragmentManager().beginTransaction().replace(R.id.pane, shoplist).addToBackStack(null).commit();  //  replace original fragment with new fragment, add original to backstack

And to override the back key to go back to the previous fragment:

publicvoidonBackPressed() {
    FragmentManager fm = getActivity().getSupportFragmentManager();
    fm.popBackStack();
    return;
}

Post a Comment for "Fragment Replacing Existing Fragment"