Fragment Replacing Existing Fragment

后端 未结 1 1888
旧巷少年郎
旧巷少年郎 2021-01-03 17:08

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

相关标签:
1条回答
  • 2021-01-03 17:28

    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;
    }
    
    0 讨论(0)
提交回复
热议问题