Android 在 onSaveInstanceState 后无法执行此操作

标签 android

这个错误是我的大问题,我阅读了越来越多的解决方案,但我无法解决,我有一些 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/

相关文章:

android - 溢出-x : hidden; not working on android devices

android - android v2 mapview 中的中心固定标记

Android Retrofit2 返回未找到(404 错误)

Android:读取 ASSETS 文件夹中的 GZIP 文件

android - 未能找到样式 vpiCirclePageIndicatorStyle

android - 如何正确保护使用应用内购买和本地数据库的应用程序

java - 方法 OnCreate(bundle) 永远不会被调用并且应用程序崩溃

android - 平滑调整图表和 map View 的大小

python - 如何使用python使用wifi?

java - 使用 android 和 Java 套接字连接到服务器,并需要用户的许可