What is the difference between commit() and commitAllowingStateLoss() in Fragments

前端 未结 2 389
后悔当初
后悔当初 2020-12-05 12:54

I was using the commit method in my project that built it with fragments.

Anyway, sometimes I was getting IllegalStateException: Can not perform this action a

2条回答
  •  没有蜡笔的小新
    2020-12-05 13:08

    commit():

    Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

    commitAllowingStateLoss():

    A transaction can only be committed with this method prior to its containing activity saving its state. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss() for situations where it may be okay to lose the commit.

    If you do commit() after onSaveInstance(), you will get below exception:

    java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
        at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
        at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
        at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
    

提交回复
热议问题