首页 文章

覆盖onSavedInstanceState:savedInstanceState对象始终为null

提问于
浏览
1

我有两个活动(A和B) . 活动A调用活动B.活动B有这样的后退(向上)按钮:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

现在,当按下此UP按钮时,再次调用onCreate of activity A . 在活动A中,有一个 classId 变量(我从 Intent 获得),我想保留它 . 为此,我在活动A的 onCreate 中有以下代码:

if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }

我也覆盖了 onSavedInstanceState 方法:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}

我正在关注这个答案:onCreate being called on Activity A in up navigation

我面临的问题是,当我通过传递活动B中的按钮再次来到活动A时,onCreate被调用,我发现savedInstanceState为NULL .

Edit:

有没有其他方法可以保存我的 classId 变量,这样当我再次返回活动A时,我可以使用它吗?

Edit 2

如果我在清单文件中将活动A的启动模式设置为 SingleTop ,我的问题就会得到解决 . 这是正确的方法吗?

3 回答

  • 0

    您不应该假设每次进入下一个活动时都会调用 onSaveInstanceState . 请参阅文档

    This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

    您可以进一步咨询官方文档here

  • 1

    试试这个

    public class SingletonHolder {
    
        //your id here as what data type you want
    
    
        private  static SingletonHolder instance;
    
        public static SingletonHolder getInstance() {
            if (instance == null) {
                instance = new SingletonHolder();
            }
            return instance;
        }
    
       //set getter setter here
    }
    

    如果不成功,请随时发表评论

  • 0

    我在 mainfest 文件中将活动A的 launchMode 更改为 singleTop ,如下所示:

    android:launchMode="singleTop"
    

    我在SO上关注了这个问题:Setting launchMode="singleTask" vs setting activity launchMode="singleTop"

    通过使用此方法,活动A不会被销毁,当我刚刚完成活动B或单击活动B中的向上导航时,活动A的现有实例将再次启动 .

相关问题