問題描述
在一個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