假设我正在创建一个具有Android
和一组Navigation drawer
的fragment
应用程序。当用户单击Navigation drawer
中的选项时,将加载相应的fragment
。该应用程序只有一个activity
(Main activity
),而没有view
。
首次启动应用程序时,哪个fragment
被加载到main activity
中? application
如何知道在没有用户交互的情况下首先加载哪个fragment
?如何将自定义fragment
设置为在应用程序启动时自动加载?
谢谢
最佳答案
您只需执行与用户交互时以及在Activity的onCreate()
方法中用于替换片段的相同FragmentTransaction。但是您必须检查一下saveInstanceState是否为null:
@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();
}
}