8

我知道http://developer.android.com/guide/components/fragments.html的图 2我想知道当我旋转屏幕并最终回到“Fragment Active”时“Fragment Active”会发生什么。

我的问题的背景是,无论我以纵向还是横向模式启动它,我都有一个可以正常工作的应用程序。但是在屏幕旋转时它会转储

Fragment com.bla.bla did not create a view.

这个片段基本上只实现了onCreateView,没有别的

public View onCreateView(LayoutInflater i, ViewGroup c, Bundle s)
{
   return i.inflate(R.layout.mylayout, c, false);
}

知道屏幕旋转到底发生了什么,我希望能解决这个问题......

编辑:

我尝试了评论者的建议,并提供了更多信息。所以他们基本上都建议有一个空的活动布局,如果我没看错的话,以编程方式添加片段。我有一个用于纵向的 main.xml 和一个用于横向的,两者现在看起来非常相似(不同之处是水平与垂直):

主.xml:

<LinearLayout xmlns:android="http:// and so on" 
    android:layout_width="fill_parent" 
    android:layout_heigt="wrap_content" 
    android:orientation=vertical" 
    android:id="@+id/myContainer">
</LinearLayout>

我的活动的 onCreate 方法如下所示:

super.onCreate(savedInstanceBundle);
setContentView(R.layout.main);

Fragment1 f1 = newFragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.myContainer, f1);
//and I need a second fragment
Fragment2 f2 = newFragment2();
ft.add(R.id.myContainer, f2);
ft.commit();

屏幕旋转似乎可以解决这个问题(到目前为止,谢谢!)但在横向中,我只看到纵向的第一个片段,我看到了两个,第二个片段多次(我旋转的次数越多,添加的次数越多)。所以要么我有布局问题,要么我不能像这样添加多个片段。仍在尝试确定这是否是布局问题,但尚无线索。有什么提示吗?

4

1 回答 1

3

我理解你的问题的方式,你不应该每次都添加片段。您应该用新片段替换当前存在的内容。

ft.replace(R.id.myContainer1, f1);
//and I need a second fragment
Fragment2 f2 = newFragment2();
ft.replace(R.id.myContainer2, f2);

至于Fragment生命周期——当你旋转屏幕时,宿主Activity会被销毁并重新创建;所以所有正确的直到onDetach()应该被调用,然后是所有以onAttach().

最可靠的方法是覆盖所有生命周期方法并在所有方法中放入日志消息:-)

于 2012-08-02T13:50:39.630 回答