保留的片段和布局更改崩溃Android应用程序

时间:2016-04-17 22:10:06

标签: android android-layout android-fragments

我正在开发一个团队的应用程序,默认情况下在所有片段上保留为true 。 我试图为我们的平板电脑设置纵向和横向布局,具有主/细节的风景,以及只有主人的肖像。在两个窗格布局的android指南之后,检查

if (findViewById(R.id.item_detail_container) != null) {
    // The detail container view will be present only in the
    // large-screen layouts (res/values-w900dp).
    // If this view is present, then the
    // activity should be in two-pane mode.
    mTwoPane = true;
}

如果我进入横向模式,在master中选择一个项目,我会添加详细信息片段:

getSupportFragmentManager().beginTransaction()
        .replace(R.id.item_detail_container, fragment)
        .commit();

如果我然后旋转为纵向,并且新布局文件没有item_detail_container,则应用程序崩溃并显示一条消息,告诉我没有视图将片段放入。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matthew.myapplication/com.example.matthew.myapplication.ItemListActivity}:
    java.lang.IllegalArgumentException: No view found for id 0x7f0c006d
    (com.example.matthew.myapplication:id/item_detail_container) for fragment ItemDetailFragment{ea138c2 #0 id=0x7f0c006d}

这是可以理解的 - 当重新创建活动时,FragmentManager会尝试从显示时找到FrameLayout

我知道我可以做的事情来解决这个问题:

  1. 停止保留详细信息片段,
  2. 让肖像布局也有该框架,通过检查DP宽度手动设置twoPane,而不是使用带有DP限定符的布局。
  3. 重新创建的步骤 - 最小完整示例:

    1. 打开android Studio并使用“Master / Detail Flow”活动创建一个新项目
    2. 在ItemDetailFragment#onCreateView中,请致电this.setRetainInstance(true);
    3. 以横向模式在平板电脑或模拟器上打开应用,然后选择任何项目,以显示详细信息窗格。
    4. 旋转至肖像。
    5. 该应用程序将崩溃。

      我之前在“嵌套片段”的上下文中看到过这个问题,但是我无法找到特定于保留片段的结果。

      是否还有另一个选项可以告诉操作系统在框架消失的情况下销毁我保留的片段,甚至离开它但是将其分离 - 这样当我旋转回横向但没有选择新项目时,它把它重新放回原位?

      感谢任何人的意见。

0 个答案:

没有答案