Android:屏幕旋转时的 fragment 生命周期

标签 android android-fragments

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

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

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

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

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

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

编辑:

我尝试了评论者的建议,并获得了更多相关信息。所以他们基本上都建议有一个空的 Activity 布局,如果我没看错的话,以编程方式添加 fragment 。我有一个用于纵向的 main.xml 和一个用于横向的 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>

我的 Activity 的 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();

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

最佳答案

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

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

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

关于Android:屏幕旋转时的 fragment 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11773581/

相关文章:

android - 无法通过无限滚动加载数据

android - 使用 LayoutParams 动态添加 fragment

android - 每次用户单击 map 时在 map View 上放置可绘制标记的有效方法是什么

android - 如何将像素(手机显示宽度)转换为毫秒(ms)?

php - 如何在不编码的情况下使用 Volley 进行多部分?

java - 旋转屏幕后, View 寻呼机保留旧 fragment

android - 即使我使用了 START_NOT_STICKY,为什么当进程被终止时我的 Android 服务会重新启动?

Android - 无法导入 google-play-services_lib,因为项目名称正在使用中

android - 如何使用 Android Build Tools 构建 Android Archive Library(AAR)?

android - 在 fragment 中按回时列表会加倍