您的位置:首页 > 编程语言 > Java开发

【Bug记录 2018-03-30】java.lang.IllegalStateException: Can not perform this action after onSaveInstance

2018-03-30 17:00 555 查看

java.lang.IllegalStateException: Can not perform this action after onSaveInstance

参考 https://blog.csdn.net/chenshufei2/article/details/48747149#t3

http://www.jb51.net/article/113723.htm

原因

首先看下onSaveInstanceState触发时机

Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a useraction (such as pressing the BACK key)

当用户按下HOME键时。

这是显而易见的,系统不知道你按下HOME后要运行多少其他的程序,自然也不知道activity A是否会被销毁,故系统会调用onSaveInstanceState,让用户有机会保存某些非永久性的数据。以下几种情况的分析都遵循该原则

长按HOME键,选择运行其他的程序时。

按下电源按键(关闭屏幕显示)时。

从activity A中启动一个新的activity时。

屏幕方向切换时,例如从竖屏切换到横屏时。

而DialogFragment#show中默认调用FragmentTransaction#commit,commit提交时不允许状态丢失,否则会抛异常.

解决方法

自己封装Fragment或者DialogFragment,重写show方法和dismiss方法

public void show(AppCompatActivity activity) {

FragmentTransaction  ft=activity.getSupportFragmentManager().beginTransaction();
ft.add(this, this.getClass().getSimpleName());
ft.commitAllowingStateLoss();//注意这里使用commitAllowingStateLoss()
}

public void dismiss() {
dismissAllowingStateLoss();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐