应用程序启动时要添加到主活动中的第一个片段 [英] First fragment to be added to the main activity when application starts up

查看:95
本文介绍了应用程序启动时要添加到主活动中的第一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在创建一个Android应用程序,该应用程序具有一个Navigation drawer和一组fragment s.当用户单击Navigation drawer中的选项时,将加载相应的fragment.该应用程序只有一个activity(Main activity),而没有view.

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.

首次启动应用程序时,哪个fragment加载到了main activity中? application如何知道在没有用户交互的情况下首先加载哪个fragment?如何将自定义fragment设置为在应用程序启动时自动加载?

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?

谢谢

推荐答案

您只需执行与用户交互以及Activity的onCreate()方法中用来替换片段的相同FragmentTransaction.但是您必须检查一下saveInstanceState是否为null:

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

这篇关于应用程序启动时要添加到主活动中的第一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆