java.lang.IllegalStateException: No activity
出现场景
第一次启动程序可以正常运行,随便切换tab也不会有问题,第二次必崩
引起BUG的原因是
当fragment移动到分离状态的时候,会重置内部状态,但是并没有重置子fragment管理器(这是类库当前版本的错误),这会让fragment复位之后使他不连接导致一个exception
解决办法是
添加 下面的代码对于每一个fragment 在onDetach()方法里
public
void
onDetach() {
super .onDetach();
try {
Field childFragmentManager = Fragment. class .getDeclaredField( "mChildFragmentManager" );
childFragmentManager.setAccessible( true );
childFragmentManager.set( this , null );
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
super .onDetach();
try {
Field childFragmentManager = Fragment. class .getDeclaredField( "mChildFragmentManager" );
childFragmentManager.setAccessible( true );
childFragmentManager.set( this , null );
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
上面是错的存在几个问题 开个玩笑
一个是mChildFragmentManager可能为空 那么在childFragmentManager.setAccessible的时候就会开始抛出空指针
二则是捕捉异常之后直接抛出了RuntimeException导致程序挂掉了 这样等于没有处理
下面这个则处理了这两个问题
try { Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager"); if (childFragmentManager != null) { childFragmentManager.setAccessible(true); childFragmentManager.set(this, null); } } catch (Exception e) { e.printStackTrace(); }