当移除或替换fragment时将事务添加到堆栈中,被移除的Fragmeng没有消亡,如果用户返回,Fragment会重新启动。如果没有放入到堆栈中,当Fragment被替换或移除,Fragment会消亡。
下面是替换Fragment的例子:
// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
addToBackStack()方法有一个可选的字符串参数,用来指定事务的唯一名称,这个是非必须的。
图二 Google IO APP