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
It's a good thing that Android Source code is Open Source when we faced some question like this!
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.
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.
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