标签:oss art throw save void log ext 队列 over
使用Fragment时。能够通过用户交互来运行一些动作。比方添加、移除、替换等。
全部这些改变构成一个集合,这个集合被叫做一个transaction。
能够调用FragmentTransaction中的方法来处理这个transaction,而且能够将transaction存进由activity管理的back stack中,这样用户就能够进行fragment变化的回退操作。
能够这样得到FragmentTransaction类的实例:
FragmentManager mFragmentManager = getSupportFragmentManager(); FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
在commit()方法之前,你能够调用addToBackStack(),把这个transaction增加back stack中去,这个back stack是由activity管理的。当用户按返回键时,就会回到上一个fragment的状态。
你仅仅能在activity存储它的状态(当用户要离开activity时)之前调用commit()。假设在存储状态之后调用commit()。将会抛出一个异常。
这是由于当activity再次被恢复时commit之后的状态将丢失。假设丢失也没关系。那么使用commitAllowingStateLoss()方法。
/** * Return the FragmentManager for interacting with fragments associated * with this activity. */ public FragmentManager getSupportFragmentManager() { return mFragments; }
/** * Container for fragments associated with an activity. */ final class FragmentManagerImpl extends FragmentManager { ........ @Override public FragmentTransaction beginTransaction() { return new BackStackRecord(this); } ........ }
/** * @hide Entry of an operation on the fragment back stack. */ final class BackStackRecord extends FragmentTransaction implements FragmentManager.BackStackEntry, Runnable { .......... public int commit() { return commitInternal(false); } 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); mCommitted = true; if (mAddToBackStack) { mIndex = mManager.allocBackStackIndex(this); } else { mIndex = -1; } mManager.enqueueAction(this, allowStateLoss); return mIndex; } .......... }
让我们回到FragmentManager,看这种方法是怎样操作的。
我们找到这种方法。
/** * @hide Entry of an operation on the fragment back stack. */ final class BackStackRecord extends FragmentTransaction implements FragmentManager.BackStackEntry, Runnable { .......... public int commit() { return commitInternal(false); } 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); mCommitted = true; if (mAddToBackStack) { mIndex = mManager.allocBackStackIndex(this); } else { mIndex = -1; } mManager.enqueueAction(this, allowStateLoss); return mIndex; } .......... }
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); } }
FragmentTransaction的commit和commitAllowingStateLoss的差别
标签:oss art throw save void log ext 队列 over
原文地址:http://www.cnblogs.com/mfmdaoyou/p/7045243.html