在onCreate中找不到片段

时间:2014-01-16 16:21:35

标签: android android-fragments

我承认我仍然在与Fragments斗争,目前我不知道在哪里加载:

起初我在我的Activity的OnCreate()中加载了我的Fragment,但后来我很难访问它(通过findViewById)并将其移动到onStart(),但我仍然无法在片段中找到视图调用onStart()...

所以在onCreate:

setContentView(R.layout.myfrag);
FrameLayout fl = (FrameLayout)findViewById(R.id.iPortraitView);  // different for Landscape
if(fl.getChildCount() == 0)  {
     getFragmentManager().beginTransaction()
    .add(R.id.iTestView, new AFragmentClass).commit();
}
else {
     getFragmentManager().beginTransaction()
    .replace(R.id.iTestView, new AFragmentClass).commit();
}
Log.d("myTest", String.valueOf(fl.getChildCount()));

现在的问题是 fl.getChildCount()总是在onCreate中返回0,从而添加新的片段,而实际上有些东西在我调用相同的代码时( fl .getchildCount())在onCreate中,我得到了正确的计数(每次更改方向时,计数明显增加)。因此,我的横向和纵向布局都有重叠的视图。

我在这里感到很茫然,并且猜测我正在努力弄清楚什么时候加载(特别是当我可以访问它们时)。此外,我是否必须为我可能在片段中动态加载的潜在视图(如各种片段中包含的按钮)实现所有监听器?

1 个答案:

答案 0 :(得分:0)

在活动片段生命周期中,Fragment的{​​{1}}尚未被调用。在onCreateView()之前调用onCreate(Bundle bundle),因此没有视图可以获取执行点的计数。查看生命周期:http://developer.android.com/guide/components/fragments.html

为了在片段上设置侦听器和其他视图修改,您需要覆盖片段中的onCreateView()方法。