片段UI元素为空

时间:2013-10-21 12:42:08

标签: java android android-fragments

我以这样的for循环以编程方式将片段添加到我的活动中:

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    for(int i = 0; i<bl.size(); i++)
    {ft.add(R.id.linearlayout, new BackflowDeviceFragment(), Integer.toString(i));}//for
    ft.commit();
    fm.executePendingTransactions();
然后,我尝试获取对这些片段的引用,如下所示:

BackflowDeviceFragment frag = (BackflowDeviceFragment) fm.findFragmentByTag(Integer.toString(i));

我成功获得了一个引用,但每当我尝试操作任何片段的UI元素时,它们都会被发现为null。所以我做了一些调试,发现我在UI元素上创建的公共方法是在onCreateView()方法之前调用的,我设置了所有的UI东西。

什么时候onCreateView()调用?如何成功使用这些UI元素?

2 个答案:

答案 0 :(得分:3)

根据片段Documentation,onCreateView():

This will be called between onCreate(Bundle) and onActivityCreated(Bundle). 

所以你不应该在初始化之前引用你的UI元素。

答案 1 :(得分:0)

希望我在放弃之前等了大约10分钟才提出这个问题。在阅读了活动生命周期后,我发现如果我在onResume()而不是onCreate()中调用这些公共方法,一切正常。如果有人有更好的解决方案,我会打开这个问题。