你能夠從FragmentManager對象中獲取一個FragmentTransaction對象的實例,例如:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
每個事務是一組想要同時執行的改變,你能夠使用諸如add()、remove()和replace()方法把想要在一個事務中執行的所有改變組合到一起,然后,調用commit()方法,把事務的執行結果反映到Activity中。
但是,在調用commit()方法之前,為了把事務添加到Fragment事務的回退堆棧,你可能要調用addToBackStack()方法。這個回退堆棧被Activity管理,並且允許用戶通過按返回按鈕返回到先前的Fragment狀態。
下例說明了怎樣用另一個Fragment替換當前的Fragment,並且在回退堆棧中保留這個Fragment的當前狀態。
// 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();
在這個例子中,newFragment替換了在布局容器中被R.id.fragment_container ID標識的任何當前Fragment。通過調用addToBackStack()方法,替換事務被保存到回退堆棧中,以便用戶能夠反轉事務,並且能夠通過按回退按鈕返回到前一個Fragment。
如果給事務添加多個改變(如用add()或remove()方法),並且調用了addToBackStack()方法,那么所有這些改變在調用commit()方法之前,都會作為一個單一的事務被添加到回退堆棧中,並且案返回按鈕時,所有這些改變將會被恢復。
除了以下兩種情況之外,添加到FragmentTransaction的改變順序無關緊要:
1. 最后必須調用commit()方法;
2. 如果給同一個容器添加了多個Fragment,那么添加的順序決定了它們在View層次樹中顯示順序。
在你執行刪除Fragment的事務時,如果沒有調用addToBackStack()方法,那么Fragment將會在事務被提交時銷毀,並且用戶不能再向后導航。因此,在刪除Fragment時,如果調用了addToBackStack()方法,那么這個Fragment就會被終止,並且用戶向后導航時將會被恢復。
提示:對於每個Fragment事務,你能夠在提交之前通過調用setTransition()方法,申請一個過渡動畫。
調用commit()方法並不立即執行這個事務,而是在Activity的UI線程之上(”main”線程)調度運行,以便這個線程能夠盡快執行這個事務。但是,如果需要,可以調用來自UI線程的executePendingTransactions()方法,直接執行被commit()方法提交的事務。通常直到事務依賴其他線程的工作時才需要這樣做。
警告:你能夠使用commit()方法提交一個只保存之前Activity狀態的事務(在用戶離開Activity時)。如果試圖在用戶離開Activity之后提交,將會發生一個異常。這是因為如果Activity需要被恢復,而提交之后的狀態卻丟失了。這種情況下,使用commitAllowingStateLoss()方法,你丟失的提交就沒問題了。
