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

最后都变了- 提交于 2019-12-20 04:53:27

问题


Suppose I am creating an Android application which has a Navigation drawer and set of fragments. When user clicks on an option in the Navigation drawer the corresponding fragment is loaded. The application has only one activity (Main activity) and it has no view.

When the application is first started which fragment gets loaded into the main activity? How does the application know which fragment to be loaded first without user interaction? How to set a custom fragment to be loaded automatically when the application starts?

Thank you


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/22557780/first-fragment-to-be-added-to-the-main-activity-when-application-starts-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!