我的異常系列目錄為:http://www.reibang.com/p/cb10697226ef
出現(xiàn)commit already called這個(gè)異常的原因是:同一個(gè)FragmentTransaction只能commit一次(調(diào)用commit方法)譬猫,可在它的實(shí)現(xiàn)類 BackStackRecord中找到以下代碼琳骡,每一個(gè)BackStackRecord對象都會(huì)維護(hù)一個(gè)布爾變量(mCommitted),當(dāng)commit后賦值這個(gè)變量為true套啤,下次再commit時(shí)會(huì)檢查這個(gè)變量硬梁,如果是true婴洼,則拋出以上異常海蔽。commit方法的源碼如下:
```java
@Override
public int commit() {
return commitInternal(false);
}
int commitInternal(boolean allowStateLoss) {
if (mCommitted) throw new IllegalStateException("commit already called");
if (FragmentManagerImpl.DEBUG) {
Log.v(TAG, "Commit: " + this);
LogWriter logw = new LogWriter(TAG);
PrintWriter pw = new PrintWriter(logw);
dump(" ", null, pw, null);
}
mCommitted = true; //這里賦值為true了
if (mAddToBackStack) {
mIndex = mManager.allocBackStackIndex(this);
} else {
mIndex = -1;
}
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}
```
綜上,我們在使用FragmentTransaction時(shí)输硝,需要保證這個(gè)對象只調(diào)用一次commit今瀑,下次commit時(shí)需要重新獲取!