How can I implement FragmentManager and FragmentTransaction to replace just a single fragment?

后端 未结 1 1591
刺人心
刺人心 2020-12-19 13:29

I have an activity with 3 fragments; a header; a body; a footer (same point as in HTML). The bodyfragment contains three buttons which each should replace the middle fragmen

相关标签:
1条回答
  • 2020-12-19 13:51

    You use the FragmentManager like this:

    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.bodyfragment, AnotherFragment.newInstance()); // newInstance() is a static factory method.
    transaction.commit();
    

    This code would replace the Fragment which sits in the View with the id R.id.bodyfragment with a new Instance of another Fragment.

    EDIT:

    To create a new instance of another Fragment a static factory method is supposed to be used. You would implement them in your Fragment like this:

    public class AnotherFragment extends Fragment {
    
        public static AnotherFragment newInstance() {
            AnotherFragment fragment = new AnotherFragment();
            ...
            // do some initial setup if needed, for example Listener etc
            ...
            return fragment;
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题