java.lang.IllegalStateException: commit already called

添加Fragment时,报如下错误:java.lang.IllegalStateException: commit already called

原因是同一个FragmentTransaction只能使用commit方法提交一次。我们可以在它的实现类 BackStackRecord中找到以下代码,每一个BackStackRecord对象都会维护一个布尔变量,即mCommitted变量,当commit后赋值这个变量为true,下次再commit时会检查这个变量,如果是true,则抛出以上异常。

commit方法的源码如下:

@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;
    if (mAddToBackStack) {
        mIndex = mManager.allocBackStackIndex(this);
    } else {
        mIndex = -1;
    }
    mManager.enqueueAction(this, allowStateLoss);
    return mIndex;
}

所以,我们在使用FragmentTransaction时,需要保证这个对象只调用一次commit,下次commit时需要重新获取!

发表回复

后才能评论