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

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

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硬编码的片段无法替换。如果需要用另一个片段替换片段,则应该首先动态添加它们。

注意: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();

以上是 Java用活动组内的另一个片段替换一个片段 的全部内容, 来源链接: utcz.com/qa/403552.html

回到顶部