显示对话框片段引发 "can not perform this action after onSaveInstanceState" 异常
Showing dialog fragment throws "can not perform this action after onSaveInstanceState" exception
有时,在某些设备上,对话片段会因上述 illegalstateexception
而崩溃 activity
我试过 shownow() ,它只在某些设备上有帮助,但问题仍然存在。
val dialog = CustomDialogFragment.newInstance(false, correctAnswer, true)
dialog.show(supportFragmentManager, "alert")
我需要对话框实例以备将来使用,否则我会在 newInstance() 之后立即使用 show。可能的解决方案是什么?
此问题的根本原因是您试图显示 FragmentDialog activity 已将其状态更改为 onPause()。
要处理此问题,您必须在显示对话框之前检查生命周期状态
if(lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)){
val dialog = CustomDialogFragment.newInstance(false, correctAnswer, true)
dialog.show(supportFragmentManager, "alert")
}
当我发现问题是由 Android 问题引起的时,我有以下解决方法:只需重写对话框片段的 show() 方法,如下所示:
@Override
public void show(@NonNull FragmentManager manager, @Nullable String tag) {
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
有时,在某些设备上,对话片段会因上述 illegalstateexception
而崩溃 activity我试过 shownow() ,它只在某些设备上有帮助,但问题仍然存在。
val dialog = CustomDialogFragment.newInstance(false, correctAnswer, true)
dialog.show(supportFragmentManager, "alert")
我需要对话框实例以备将来使用,否则我会在 newInstance() 之后立即使用 show。可能的解决方案是什么?
此问题的根本原因是您试图显示 FragmentDialog activity 已将其状态更改为 onPause()。
要处理此问题,您必须在显示对话框之前检查生命周期状态
if(lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)){
val dialog = CustomDialogFragment.newInstance(false, correctAnswer, true)
dialog.show(supportFragmentManager, "alert")
}
当我发现问题是由 Android 问题引起的时,我有以下解决方法:只需重写对话框片段的 show() 方法,如下所示:
@Override
public void show(@NonNull FragmentManager manager, @Nullable String tag) {
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}