The difference between Android commitAllowingStateLoss and commit() switching fragments

commit()and commitAllowingStateLoss()are two methods used to submit FragmentTransaction in Android's FragmentManager. The main difference between them is the way of handling "state loss".

  1. commit() : When this method commits a transaction, if the state has been saved (that is, the Activity's onSaveInstanceState() method has been called), then it will throw an exception. This is because FragmentManager will save the rollback stack of the transaction after the state is saved, so if a transaction is committed after the state is saved, the transaction will not be saved in the rollback stack. This can lead to an inconsistent state when the app restores state.

  2. commitAllowingStateLoss() : This method allows a transaction to be committed after the state has been saved, even if this would result in state loss. It will not throw an exception for state loss, but if the transaction is committed after the state is saved, the transaction will not be saved in the rollback stack, which may cause an inconsistent state when the application restores the state.

In general, you should try to avoid committing transactions after the state has been saved, because this may cause the application's user interface state to be inconsistent with the actual application state. But in some cases, you may want to use commitAllowingStateLoss(), for example, when your app can tolerate losing UI state under certain circumstances.

Guess you like

Origin blog.csdn.net/mp624183768/article/details/130863398