【发布时间】:2023-03-26 12:41:01
【问题描述】:
在 Android 教程中,在 Building a Flexible UI 下,示例中给出的 Fragment 实例化发生在 Activitiy 的 onCreate() 中,如下所示:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
...
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
不包括 if (findViewById(R.id.fragment_container) != null) 检查,我自己的示例在启动时失败:
IllegalStateException:指定的孩子已经有一个父母。您必须先在孩子的父母上调用 removeView()。
我的问题是:
if 检查有什么作用?我不明白教程示例中的注释解释。我的理解是,由于某种原因,onCreate() 在活动生命周期中被不止一次调用,但我不知道为什么?诚然,我对活动生命周期的了解很少。
【问题讨论】:
标签: android dynamic android-fragments