应用程序启动时要添加到主活动中的第一个片段 [英] First fragment to be added to the main activity when application starts up
问题描述
假设我正在创建一个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 fragment
s. 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屋!