问题
我在组活动中有一个片段,我想用另一个片段替换它:
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方法中,我希望当用户点击水平滚动视图中的项目时,片段会发生变化。
#1 热门回答(224 赞)
**无法替换以XML格式编码的片段。**如果你需要用另一个片段替换片段,你应该首先动态添加它们。
注意:R.id.fragment_container是你将片段带入的活动中所选择的布局或容器。
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().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();
#2 热门回答(29 赞)
请参阅thisQuestion
你只能替换"动态添加的片段"。
因此,如果要添加动态片段,请参阅thisexample。
#3 热门回答(8 赞)
我做了一个要点完美的方法管理片段****替换and生命周期。
它只用一个新片段替换当前片段,如果它不相同并且它不在backstack中(在这种情况下它将弹出它)。
它包含几个选项,就好像你希望将片段保存在backstack中一样。
使用此活动和单个活动,你可能希望将其添加到你的活动中:
@Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}