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

2023-12-23

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

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() 时,日志猫中的每件事都工作得很好,但没有视图可见,甚至没有出现任何异常,我希望书籍详细信息片段被部分细节片段替换。

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

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


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

Note: 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将一个片段替换为活动组内的另一个片段 的相关文章

随机推荐