我正在阅读 Android 编程,书中说:
It is entirely possible that an activitys onCreate will be called while it is still associated with a previously created fragment. Simply adding a new fragment whenever onCreate method is called will leak fragments. To prevent that, the example code makes use of the fragment managers tagging and location features.
代码是:
super.onCreate( state);
setContentView( R.layout.main);
FragmentManager fragMgr = getFragmentManager();
FragmentTransaction xact = fragMgr.beginTransaction();
if (null = = fragMgr.findFragmentByTag( FRAG1_TAG)) {
xact.add( R.id.date_time, new DateTime(), FRAG1_TAG);
}
xact.commit();
有人可以解释为什么在 onCreate 中需要这样做吗?
我认为 fragment 生命周期总是依赖于 Activity 的生命周期,并且 Activity 中的 onCreate 总是在 Activity 创建时被调用(即它总是死的)。
因此,如果 fragment 生命周期与 Activity 相关联,那么当 Activity 死亡时,不应该所有 fragment 都死亡,因此在 Activity 中调用 onCreate 时 fragment 将始终为空?
是否有异常(exception)或有人可以解释为什么我的想法不正确(我实际上认为它不正确但不知道为什么?)
最佳答案
fragment 将被 Activity
销毁但是 FragmentManager
除非您完全完成 Activity
,否则会记住它们。 .如果 Activity
由于配置更改而被杀死,然后重新创建 FragmentManager
需要恢复任何以前提交的 fragment 。这就是为什么您要检查 Fragment
尚未在 FragmentManager
中.如果它在那里,则中止事务,否则将以两个 fragment 结束(您刚刚创建的新 fragment 和 FragmentManager
记住的旧 fragment ,它将恢复)。
关于android - onCreate 中的 fragment 创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989720/