【问题标题】:Android: Fragment lifecycle on screen rotationAndroid:屏幕旋转的片段生命周期
【发布时间】:2012-08-02 08:21:02
【问题描述】:

我知道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 和一个用于横向的,两者现在看起来非常相似(不同之处是水平与垂直):

main.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();

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

【问题讨论】:

标签: android android-fragments


【解决方案1】:

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

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() 开头的所有内容。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2020-07-14
    相关资源
    最近更新 更多