I have an activity with below layout
maybe your can encapture commition of FragmentTransaction like this
private void commitFragmentTransaction(final FragmentTransaction ft, boolean allowStateLoss, boolean now) {
if (ft == null || ft.isEmpty()) {
return;
}
if (allowStateLoss) {
if (now) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ft.commitNowAllowingStateLoss();
} else {
ft.commitAllowingStateLoss();
mFragmentManager.executePendingTransactions();
}
} else {
ft.commitAllowingStateLoss();
}
} else {
if (now) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ft.commitNow();
} else {
ft.commit();
mFragmentManager.executePendingTransactions();
}
} else {
ft.commit();
}
}
}
commitNow() and commitNowAllowingStateLoss() is Added in API level 24
Calling commitNow is preferable to calling commit() followed by executePendingTransactions() as the latter will have the side effect of attempting to commit all currently pending transactions whether that is the desired behavior or not.
Yes the transaction is committed asynchronously. If you want to make sure all trasactions have finished before executing isAdded
, run:
getFragmentManager().executePendingTransactions();
From documentation for executePendingTransactions():
After a FragmentTransaction is committed with FragmentTransaction.commit(), it is scheduled to be executed asynchronously on the process's main thread. If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. Note that all callbacks and other related behavior will be done from within this call, so be careful about where this is called from.
So your code should look like:
removeFragmentsInActivity(R.id.frameLayoutB,fragB);
addFragmentsInActivity(R.id.frameLayoutB,fragC);
getFragmentManager().executePendingTransactions();
if(!fragB.isAdded()){
Log.e("check", "fragB already removed from frameLayoutB");
removeFragmentsInActivity(R.id.frameLayoutA,fragA);
addFragmentsInActivity(R.id.frameLayoutA,fragB);
}
else{
Log.e("check", "fragB already added");
}
Note also fixed removing of fragment A.