Android UI基础教程:使用Fragment构建灵活的桌面(2)

当移除或替换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()方法有一个可选的字符串参数,用来指定事务的唯一名称,这个是非必须的。

参考:

Android UI基础教程:使用Fragment构建灵活的桌面

图二 Google IO APP

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/c2e2225c7739ecccf4993eef9ee3df32.html