使用:
通常使用FragmentTransaction来add、replace、remove需要操作的fragment,然后通过commit或commitAllowingStateLoss应用这些变化。
关于Fragment的commit与commitAllowingStateLoss,有什么差别呢?
比如:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.m_container, new RecyclerListFragment());
//fragmentTransaction.commit();
fragmentTransaction.commitAllowingStateLoss();
结论:
-
commit() : 需要状态保持。即只能使用在在activity的状态存储之前,即在onSaveInstanceState(Bundle outState)之前调用,否则会抛异常。
-
commitAllowingStateLoss() : 允许状态丢失。
![](https://img.haomeiwen.com/i1972602/104cdf3dc8f75646.png)
分析:
commit() 和 commitAllowingStateLoss() 的具体实现是在BackStackRecord这个类里,
如下:
@Override
public int commit() {
return commitInternal(false);
}
@Override
public int commitAllowingStateLoss() {
return commitInternal(true);
}
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);
pw.close();
}
mCommitted = true;
if (mAddToBackStack) {
mIndex = mManager.allocBackStackIndex(this);
} else {
mIndex = -1;
}
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}
mManager.enqueueAction(this, allowStateLoss)
则在FragmentManager中,在此进行了状态检查checkStateLoss()
,如下:
/**
* Adds an action to the queue of pending actions.
*
* @param action the action to add
* @param allowStateLoss whether to allow loss of state information
* @throws IllegalStateException if the activity has been destroyed
*/
public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
if (!allowStateLoss) {
checkStateLoss();
}
synchronized (this) {
if (mDestroyed || mHost == null) {
throw new IllegalStateException("Activity has been destroyed");
}
if (mPendingActions == null) {
mPendingActions = new ArrayList<>();
}
mPendingActions.add(action);
scheduleCommit();
}
}
private void checkStateLoss() {
if (mStateSaved) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
if (mNoTransactionsBecause != null) {
throw new IllegalStateException(
"Can not perform this action inside of " + mNoTransactionsBecause);
}
}
扩展 :
DialogFragment的dismiss()
与dismissAllowingStateLoss()
也是同理,最终也是通过FragmentTransaction的 commit 与 commitAllowingStateLoss 来操作。
![](https://img.haomeiwen.com/i1972602/c72370954acc91de.png)
网友评论