用活动组内的另一个片段替换一个片段

新手上路,请多包涵

我在小组活动中有一个片段,我想用另一个片段替换它:

 FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

当它作为一个单独的项目完成而不使用活动组时它工作正常,当控制进入 getview() 时,log cat 中的每件事都工作正常,但没有视图可见,甚至没有出现任何异常,我希望书籍详细信息片段由部分详细信息片段替换。

书籍详细信息片段的 xml 具有 id book_description_fragment,章节描述片段的 xml 具有 id section_description_fragment。

上面的代码在项目的 onClick 方法中,我希望当用户在水平滚动视图中点击项目时,片段会发生变化。

原文由 Lion Heart 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
1 个回答

无法替换以 XML 硬编码的片段。 如果您需要用另一个片段替换一个片段,您应该首先动态添加它们。

注意: R.id.fragment_container 是您在将片段带到的活动中选择的布局或容器。

 // Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

原文由 C– 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题