First fragment to be added to the main activity when application starts up

后端 未结 1 1738
慢半拍i
慢半拍i 2021-01-21 02:13

Suppose I am creating an Android application which has a Navigation drawer and set of fragments. When user clicks on an option in the

1条回答
  •  走了就别回头了
    2021-01-21 02:31

    You just perform the same FragmentTransaction you use to replace the fragment on user interaction and in the onCreate() method of your Activity. But you have to check if savedInstanceState is null like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        if(savedInstanceState == null) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.flFragmentContainer, MainFragment.newInstance());
            transaction.commit();
        }
    }
    

    0 讨论(0)
提交回复
热议问题