这个错误是我的大问题,我阅读了越来越多的解决方案,但我无法解决,我有一些 Activity fragment ,我用这段代码替换了 fragment :
if (mSelectedMenuItem != 2) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
transaction.replace(R.id.menu_containers, fragment);
transaction.commit();
}
}, duration);
}
错误:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
和我的onSaveInstanceState
:
@Override
protected void onSaveInstanceState(Bundle outState) {
// Bug in android version > 11
//super.onSaveInstanceState(outState);
outState.putInt("selectedMenuItem", selectedMenuItem);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
selectedMenuItem = savedInstanceState.getInt("selectedMenuItem");
}
最佳答案
您在使用 postDelayed()
时自找麻烦。该应用程序可能会在执行此操作之前被终止:
new Handler().postDelayed(new Runnable() {
使用可以使用commitAllowingStateLoss()
(以避免IllegalStateException 错误)但只能作为最后的手段。调用commit()
和commitAllowingStateLoss()
的唯一区别是后者在状态丢失时不会抛出异常。通常你不想使用这种方法,因为它意味着有可能发生状态丢失。当然,更好的解决方案是编写您的应用程序,确保在保存 Activity 状态之前调用 commit()
,因为这会带来更好的用户体验。除非无法避免状态丢失的可能性,否则不应使用 commitAllowingStateLoss()
。
关于Android 在 onSaveInstanceState 后无法执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40989482/