Balaji
Balaji

Reputation: 3

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 the new Fragment2, on button click of Fragment1, Fragment2 should replace the Fragment1, and should have the same ListFragment at left, and back buttons should be properly handled,this means when I am in Fragment2 and press back button it should show the same ListFragment and Fragment1.

Upvotes: 0

Views: 11038

Answers (1)

Barak
Barak

Reputation: 16393

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 = new MenuFragment_Main();   // instantiate fragment
getSupportFragmentManager().beginTransaction().replace(R.id.pane, menu).commit();  // display fragment

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

ListFragment_ShopListItem shoplist = new ListFragment_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:

public void onBackPressed() {
    FragmentManager fm = getActivity().getSupportFragmentManager();
    fm.popBackStack();
    return;
}

Upvotes: 8

Related Questions