使用:
//获取Fragment管理器
val mFragmentManager = supportFragmentManager
//开启事务
val mTransaction = mFragmentManager.beginTransaction()
.....
mTransaction.commitAllowingStateLoss()
为什么不使用commit而是用commitAllowingStateLoss()
FragmentTransaction.java
public abstract int commitAllowingStateLoss();
实现类:BackStackRecord.java
@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(" ", pw);
pw.close();
}
mCommitted = true;
if (mAddToBackStack) {
mIndex = mManager.allocBackStackIndex(this);
} else {
mIndex = -1;
}
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}
FragmentManagerImpl.java
public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
if (!allowStateLoss) {
//关键不同在于该方法
checkStateLoss();
}
synchronized (this) {
if (mDestroyed || mHost == null) {
if (allowStateLoss) {
// This FragmentManager isn't attached, so drop the entire transaction.
return;
}
throw new IllegalStateException("Activity has been destroyed");
}
if (mPendingActions == null) {
mPendingActions = new ArrayList<>();
}
mPendingActions.add(action);
scheduleCommit();
}
}
private void checkStateLoss() {
if (isStateSaved()) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
}
@Override
public boolean isStateSaved() {
// See saveAllState() for the explanation of this. We do this for
// all platform versions, to keep our behavior more consistent between
// them.
return mStateSaved || mStopped;
}
Parcelable saveAllState() {
......
mStateSaved = true;
mStateSaved 是又saveAllState()决定的,其他状态都是false。而 saveAllState()发生在所依托的Activity调用onSaveInstanceState()。 所以commit()和commitAllowingStateLoss()的差别是是否允许Fragment是被丢失过的。
问题2:Frgament的重叠
参考链接
Fragment的Hidden默认是false,而且FragmentState没有这个词条,导致了hide的Fragement在onSaveInstanceState()后出现Fragment重叠现象。
如
下面这个音乐播放进度控制是不应该出现在这里。发生了Fragment重叠。