Save activity state(not just some variables) on orientation change

不问归期 提交于 2019-12-05 01:59:52

问题


I realized that there are lots of question on this topic already asked on SO. But I don't even know the basic when it comes to saving the state of an activity.


(Refer Screenshot Below) When app launches,

1) ScrollView item 1,2,3,4 are visible

2) table containd data which is populated due to Gainer button.


As showed in below screenshots, While app is running in PORTRAIT mode, I

1)scrolled down to ScrollView item 4,5,6

2)pressed the Loser button so accordingly data in the table below the button changes.

3)I'll even change content of graph dynamically(which I had not done yet).


Now I switch to LANDSCAPE Mode so

1)ScrollView is showing ScrollView item 1,2,3,4

2)table is showing data which is populated due to pressing Gainer button.

3)graph is as it is as I've not changed it yet(which I will change later).


So what happens is when I change the orientation, my activity is getting re-launched. So if user is performing some task in one orientation and he changes the orientation, then whole progress will be lost.

I know I need to save the state of the activity and Restore it when orientation changes. But I don't know from where to start and what to save.

ANY HELP WILL BE LIFE-SAVER !


回答1:


Option #1: Override onSaveInstanceState() of your Activity and put whatever information you want in the supplied Bundle. Your new activity instance will receive that Bundle in onRestoreInstanceState() (or onCreate()). Here is a sample project demonstrating this.

Option #2: Override onRetainNonConfigurationInstance() of your Activity and return some object that represents your state. Your new activity instance can call getLastNonConfigurationInstance() to retrieve that object, so the new activity can apply that information. Be careful, though, not to have the old activity return something in the object that holds a reference back to the old activity (e.g., a widget, an instance of a regular inner class). Here is a sample project demonstrating this.

Option #3: Convert this activity to a fragment. Have the fragment call setRetainInstance(true); on itself during its initial setup. Add the fragment dynamically to some activity via a FragmentTransaction. Now, when the configuration changes, the fragment is retained, so all your widgets and state are retained. Here is an overly-complex sample application demonstrating this.

Those are the three recommended approaches nowadays.



来源:https://stackoverflow.com/questions/8542560/save-activity-statenot-just-some-variables-on-orientation-change

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