How to prevent custom views from losing state across screen orientation changes

后端 未结 9 1053
时光说笑
时光说笑 2020-11-22 10:11

I\'ve successfully implemented onRetainNonConfigurationInstance() for my main Activity to save and restore certain critical components across screen orientation

9条回答
  •  迷失自我
    2020-11-22 10:57

    Instead of using onSaveInstanceState and onRestoreInstanceState, you can also use a ViewModel. Make your data model extend ViewModel, and then you can use ViewModelProviders to get the same instance of your model every time the Activity is recreated:

    class MyData extends ViewModel {
        // have all your properties with getters and setters here
    }
    
    public class MyActivity extends FragmentActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // the first time, ViewModelProvider will create a new MyData
            // object. When the Activity is recreated (e.g. because the screen
            // is rotated), ViewModelProvider will give you the initial MyData
            // object back, without creating a new one, so all your property
            // values are retained from the previous view.
            myData = ViewModelProviders.of(this).get(MyData.class);
    
            ...
        }
    }
    

    To use ViewModelProviders, add the following to dependencies in app/build.gradle:

    implementation "android.arch.lifecycle:extensions:1.1.1"
    implementation "android.arch.lifecycle:viewmodel:1.1.1"
    

    Note that your MyActivity extends FragmentActivity instead of just extending Activity.

    You can read more about ViewModels here:

    • Android Developer Guide, Handle configuration changes
    • Android Developer Guide, Saving UI States, Use ViewModel to handle configuration changes
    • Tutorial ViewModels : A Simple Example

提交回复
热议问题