[关闭]
@946898963 2020-06-11T12:01:11.000000Z 字数 1225 阅读 781

Fragment扩展四

Android学习笔记


异常

  1. Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

出现场景

  • 在系统调用activity的onSaveInstanceState()方法后加载fragment时(commit,dismiss,show等操作)会报上述异常。
  • 系统调用了onSaveInstanceState方法后,用户调用了onBackPressed方法。

场景一解决方案

在onSaveInstanceState方法中调用onStateNotSaved()方法(生活始末项目中就是使用的这个方法):

  1. @Override
  2. protected void onSaveInstanceState(Bundle outState) {
  3. super.onSaveInstanceState(outState);
  4. onStateNotSaved();
  5. }

这种方法是有风险的,风险建议阅读参考链接。

或者在业务允许情况下,使用commitAllowingStateLoss代替commit,使用dismissAllowingStateLoss代替dismiss,尽量不要调用show,可以通过调用fragmentTransaction.add,然后再commitAllowingStateLoss。这种方案同样是有风险的,风险建议阅读参考链接。

场景二解决方案

在onSaveInstanceState方法中调用onStateNotSaved()方法(生活始末项目中就是使用的这个方法):

  1. @Override
  2. protected void onSaveInstanceState(Bundle outState) {
  3. super.onSaveInstanceState(outState);
  4. onStateNotSaved();
  5. }

风险同上。

参考链接:

Android commit和commitAllowingStateLoss区别及应用场景 (业务场景参考这个,同时也介绍了使用commitAllowingStateLoss方法的风险)

Fragment的checkStateLoss IllegalStateException: Can not perform this action after onSaveInstanceStat(提到了dismissAllowingStateLoss方法,同时也提到了onStateNotSaved()的风险)

Android-Fragment的一些坑总结/(关于onBackPressed()这个异常场景,提到了更多解决方案)

Activity.onBackPressed()的时候抛出Can not perform this action after onSaveInstanceState的异常(提到了onBackPressed()这个异常场景,简单介绍了原因)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注