Android:来自同一 XML 文件的多个片段

Android: Multiple Fragments from same XML file

我有一个视图寻呼机,其中包含数组中每个主题(英语、数学、科学等)的页面。视图分页器中的片段都是从同一个 XML 文件创建的。然后在这些片段中添加片段。 由于所有 parents 从同一个 XML 文件膨胀,我无法指定要将 child 片段添加到哪个片段。我想知道他们是否可以做到这一点 - 也许可以缩小 id 的范围??

首先。我建议你尽量避免使用子片段,如果你真的没有很好的理由使用它们的话。

但是我不明白哪里出了问题。如果更多片段使用相同的 XML 进行膨胀,我看不出有任何问题。您可以在所有父片段上调用 ​​setArguments() 并在此处放置一些 Bundle,可用于通过 getArguments().

识别它在其中的哪个片段

我认为您想实现多个片段,并能够根据用户的选择来操作它们。有GooglelinkFragments

查看该网页上的这些代码:

  1. FragmentFragmentTransaction的多个样本
  2. 例如,查看 class TitlesFragment 中的方法 showDetails

如果您想要工作示例,请查看 Working with Android Fragments。网页片段:

<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="match_parent">
  <fragment
    android:id="@+id/headFrag"
    android:name="com.intertech.HeaderFrag"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
  <fragment
    android:id="@+id/bodyFrag"
    android:name="com.intertech.BodyFrag"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
</LinearLayout>

和代码

...
    FragmentManager fragmentManager = getFragmentManager ();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
    // work here to change Activity fragments (add, remove, etc.).
    fragmentTransaction.add (R.id.myFrame, myFrag);
    fragmentTransaction.commit ();

从上面看,布局中有 2 个片段。 fragmentTransaction.add 方法应该以 R.id 形式指定父容器。

有一天我可能会 want/need 实现它。到目前为止,我实现了 show/hide Layouts 而不是(不后悔),他们可以有 ID 供我操作。 Tommy Kwee,祝您玩得开心,随时关注我们。