2

我正在使用 getLastNonConfigurationInstance() 来保存对象,同时在我的活动中更改方向。现在它已被弃用。最好的替代方法是什么?文档说“使用片段”。但我需要使用活动。

4

1 回答 1

3

对于保存状态,使用onSaveInstanceState(Bundle savedInstanceState). 您可以在onCreate或 中恢复保存的状态onRestoreInstanceState(Bundle savedInstanceState)

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      savedInstanceState.putBoolean("MyBoolean", true);
      savedInstanceState.putDouble("myDouble", 1.9);
      savedInstanceState.putInt("MyInt", 1);
      savedInstanceState.putString("MyString", "Hello Android");
      super.onSaveInstanceState(savedInstanceState);
    }

Bundle本质上是一种存储“键值对”映射的方式,它将被传递给 onCreate 和 onRestoreInstanceState,您可以在其中提取如下值:

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      // Restore UI state from the savedInstanceState.
      // This bundle has also been passed to onCreate.
      boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
      double myDouble = savedInstanceState.getDouble("myDouble");
      int myInt = savedInstanceState.getInt("MyInt");
      String myString = savedInstanceState.getString("MyString");
    }
于 2012-05-31T10:20:25.723 回答