Fragment崩溃,再启动重叠
今天项目在测试过程中,在极端滑动Recyclerview情况下,App会崩溃。再启动App进入首页,发现之前的Fragment一直存在,首页的Fragment切换效果无法实现。
在查阅资料后,发现问题,并将之实现修复。
- 产生原因
1、首页Fragment在切换时,使用了show()和hide()方法。当出现崩溃时,首页MainActivity被销毁,此时,onSaveInstanceState() 方法会将相关数据进行保存。
2、重启App进入MainActivity中,onCreate(Bundle savedInstanceState) 方法,通过savedInstanceState 将之前保存的数据进行了恢复。
3、这种情况下,崩溃前show的Fragment 通过addFragment方式重新加载,从而导致fragment的show()和hide()方法失效,从而出现重叠效果。 - 解决方法
方法1:重写 onSaveInstanceState(Bundle outState) 方法
protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState); // 重写该方法,并注释掉该行。
}
方法2:
未雨绸缪,在通过FragmentTransaction的 add() 方法添加Fragment时,使用带 Tag 方法对所有添加的fragment进行标记。
public abstract FragmentTransaction add(@IdRes int containerViewId, Fragment fragment,
@Nullable String tag);
然后,在onCreate(Bundle savedInstanceState)方法中,对savedInstanceState进行处理!从而解决掉Fragment重叠问题
(https://img-blog.youkuaiyun.com/20161107160615076)