我的异常系列目录为:http://www.jianshu.com/p/cb10697226ef
出现commit already called这个异常的原因是:同一个FragmentTransaction只能commit一次(调用commit方法),可在它的实现类 BackStackRecord中找到以下代码,每一个BackStackRecord对象都会维护一个布尔变量(mCommitted),当commit后赋值这个变量为true,下次再commit时会检查这个变量,如果是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时,需要保证这个对象只调用一次commit,下次commit时需要重新获取!