Replace one fragment with an another fragment

前端 未结 8 1547
再見小時候
再見小時候 2020-12-16 19:37

I want to replace an old Fragment with a new Fragment, but i still get the buttons of the old Fragment that is still visible in the ne

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 20:14

    To understand the flow of fragment transition, first of all, you have to know about its structure in activity. Let's see: a) Activity: At bottom of everything (MainActivity)

    activity_main.xml :-

    
    
        
    
    

    Here @+id/container is the layout over we do transitions of fragment contents.

    B) FragmentA : Initially added fragment to the container of MainActivity.

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    //Instance of fragment
    Fragment newFragment = FragmentA.newInstance("a","b");
    //It will replace the fragment content view to container of main activity
    ft.replace(R.id.container, newFragment);
    //FragmentA is added to back stack with it's name as a tag
    ft.addToBackStack(FragmentA.class.getSimpleName());
    ft.commitAllowingStateLoss();
    

    B) FragmentB : Replace FragmentA with FragmentB

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    //Instance of fragment
    Fragment newFragment = FragmentB.newInstance("a","b");
    //It will replace the fragment content view to container of fragment A which     // is previously replaced to main activity container
    ft.replace(R.id.container, newFragment);
    //FragmentB is added to back stack with it's name as a tag
    ft.addToBackStack(FragmentB.class.getSimpleName());
    ft.commitAllowingStateLoss();
    

    So main thing behind this is to replace/add fragment content view to the activity container view.

提交回复
热议问题