Orientation Changes in android

懵懂的女人 提交于 2019-12-11 01:41:47

问题


I am using getLastNonConfigurationInstance() to save object while changing orientation in my activity. now it is deprecated. What is the best way of alternative? the documentation says "use Fragment". But i need to use activity.


回答1:


For saving state, use onSaveInstanceState(Bundle savedInstanceState). You can restore saved state either in onCreate or in 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);
    }

The Bundle is essentially a way of storing a Key-Value Pair" map, and it will get passed in to onCreate and also onRestoreInstanceState where you would extract the values like this:

    @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");
    }


来源:https://stackoverflow.com/questions/10831429/orientation-changes-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!