问题描述
在一个activity中,有定时任务,到时间后弹出一个DialogFragment,如果弹出的时候,已经跳转到了下一个activity,就会报错:Can not perform this action after onSaveInstanceState
。
解决方案
在DialogFragment中另写一个show方法:
public void showAllowingStateLoss(FragmentManager manager, String tag) {
try {
Field dismissed = DialogFragment.class.getDeclaredField("mDismissed");
dismissed.setAccessible(true);
dismissed.set(this, false);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
Field shown = DialogFragment.class.getDeclaredField("mShownByMe");
shown.setAccessible(true);
shown.set(this, true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
使用的时候,不再使用dialog.show()
,而用我们自己写的方法dialog.showAllowingStateLoss()
,就可以了!
原因分析
可以参考:解决java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState