如何重新创建片段而不添加其先前的状态

时间:2014-01-20 08:17:40

标签: android fragment

我想创建或刷新片段而不添加以前的状态。我搜索了很多东西但没找到任何合适的方法。请给我一些建议.......

1 个答案:

答案 0 :(得分:0)

你最好的选择是FragmentTransaction.replace()

E.g:

// 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
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

但是,请记住,您只能添加一次Fragment类的单个实例。尝试再次添加相同的实例将导致Fragment already added异常。要解决此问题,请使用MyFragmentClass.instantiate()new MyFragmentClass()获取需要添加的Fragment类的新实例。

相关问题