3 回答
![?](http://img1.sycdn.imooc.com/54584e120001811202200220-100-100.jpg)
TA贡献1829条经验 获得超7个赞
以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();
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
TA贡献1936条经验 获得超6个赞
我已经用完美的方法来管理片段 替换和生命周期。
它只用一个新片段替换当前片段,如果它不相同并且它不在backstack中(在这种情况下它将弹出它)。
它包含几个选项,就好像您希望将片段保存在backstack中一样。
=> 见这里的要点
使用此活动和单个活动,您可能希望将其添加到您的活动中:
@Overridepublic void onBackPressed() { int fragments = getSupportFragmentManager().getBackStackEntryCount(); if (fragments == 1) { finish(); return; } super.onBackPressed();}
添加回答
举报