【问题标题】:Changing fragments with FragmentTransaction not working?使用 FragmentTransaction 更改片段不起作用?
【发布时间】:2013-08-07 01:44:32
【问题描述】:

当用户在一个片段中单击ListView 中的元素时,会通过一个界面通知侦听器,并且它应该更改菜单旁边的片段。

我当前的代码如下所示

Fragment f = null;

switch(fragmentId) {
    case 0:
        f = new xFragment();
        break;
    case 1:
        f = new yFragment();
        break;
    ...
}

System.out.println(f.getClass().getName()); // Prints the name of the class correctly

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, f);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

当我从菜单中选择某个选项时,将调用包含该片段的活动中的此函数。它正确打印了fragmentId,并且类的名称是正确的,如代码示例中所述。

但是,片段没有改变。我尝试用new xFragment() 替换replace 方法中的f 变量,但没有帮助。

XML 布局文件如下所示。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment 
        android:id="@+id/menuFragment"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:name="fi.peltoset.mikko.home.Navigation" />

    <LinearLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical" >
    </LinearLayout>
</LinearLayout>

LinearLayout fragmentContainer 是片段的容器。

在启动时,我使用上面显示的相同代码,只是我将replace 更改为add 以在应用程序启动时添加正确的片段。这很好用。

怎么了?

【问题讨论】:

  • 你使用的是哪个版本的android sdk?

标签: java android android-fragments


【解决方案1】:

您是否尝试替换 ID 为“menuFragment”的片段?如果是这样,那么您不能这样做,因为 XML 布局中指定的任何片段都无法替换。

【讨论】:

  • 不,我不是。我正在尝试替换 LinearLayout fragmentContainer 中动态添加的片段。
【解决方案2】:

你可以尝试用 FrameLayout 替换 LinearLayout 吗?

请参考https://groups.google.com/forum/#!topic/android-developers/gAhaoLlBob4,即使没有人解释原因。

【讨论】:

【解决方案3】:

您的目标是什么版本的 Android?

尝试使用支持片段管理器:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#getSupportFragmentManager()

【讨论】:

  • 最小值为 14,目标为 17。如果我尝试使用 getSupportFragmentManager() 方法,Eclipse 会出错。适用于哪个级别?
  • getSupportFragmentManager 适用于 API 级别 10 及更低级别,如果您的最低级别为 14,则不需要它。您可以发布更多代码吗?你的片段是什么样的?我认为您发布的 sn-ps 没有任何问题。
【解决方案4】:

首先,“fragmentContainer”本身并不是一个片段。此外,您不能相互替换静态片段。它们必须是“动态添加”的片段。看看this post

要替换动态创建的片段,请查看this post

【讨论】:

  • 是的,不是。我知道我无法替换在 XML 布局中创建的片段。正如我所说,片段是动态添加到 LinearLayout 中的。您的第二个链接不是 SO 帖子,也没有说明如何替换动态创建的片段。
  • 对不起;第一个链接是 SO 帖子,而不是第二个。
  • 或者可能从使用 add() 而不是 replace() 开始..(即使 replace 有效地删除了子片段)
  • 另外,您可以检查 fragment.isInLayout()。如果这是真的,那么片段已经被添加,并且可能由于某种原因不可见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多