How is the new FragmentTransaction commitNow() working internally?

后端 未结 2 1185
[愿得一人]
[愿得一人] 2020-12-24 00:31

The new commitNow() method added in Android N and support library version 24 has a limited and a bit confusing documentation.

Commits this transaction sy

相关标签:
2条回答
  • 2020-12-24 00:45

    It's a good thing that Android Source code is Open Source when we faced some question like this!

    Answer

    So let's take a look at BackStackRecord source here

    @Override
    public void commitNow() {
        disallowAddToBackStack();
        mManager.execSingleAction(this, false);
    }
    
    @Override
    public FragmentTransaction disallowAddToBackStack() {
        if (mAddToBackStack) {
            throw new IllegalStateException(
                    "This transaction is already being added to the back stack");
        }
        mAllowAddToBackStack = false;
        return this;
    }
    

    And mAddToBackStack will be set to true if you call addToBackStack in your transaction.

    So to answer your question, no addToBackStack isn't called internally when you call commitNow(), It's the exception message that ambigous. I think it should say You're not allowed to add to backstack when using commitNow() instead the current message.

    Bonus:

    If we dig deeper into FragmentManager source code here, commitNow() actually doing almost same thing as executePendingTransactions() like written above, but instead executing all previously committed transaction, commitNow() will only commit that transaction.

    I think that's the main reason why commitNow() isn't allowing addition to the backstack since it cannot guarantee there aren't any other pending transaction. If commitNow() can add to the backstack, there is a possibility that we can break our backstack sequence that will leading into unexpected thing.

    0 讨论(0)
  • 2020-12-24 00:57

    Long story short,

    If you are using addToBackStack() with Fragment do not use commitNow() use commit() instead.

    Using Fragment with addToBackStack() and commitNow() leads to inconsistent fragment transaction ordering and hence commit() must be used.

    For detail description look this article

    0 讨论(0)
提交回复
热议问题