简体   繁体   中英

Restoring instance variables in Android upon activity recreation

I have an Android project for which I am creating a custom tab view. I have structured the main Activity ( FragmentActivity ) in such a way that it has a tab bar at the bottom of the screen with a FrameLayout above it. Each option on the tab creates a new Fragment (relating to that option). Now, to prevent recreation of fragments each time an option is clicked, I store the fragment in an instance variable in the activity. So, when a tab option is clicked, I check if its fragment is already created, if it is not already created, I create and add it to the FrameLayout (and hide any existing fragment), otherwise, I just hide the existing fragment (stored in an instance variable called currentlyViewedFragment ) and show the already created fragment that matches the clicked option.

Also when the onCreate() of the activity is called, I set the initial tab to be the home tab (one of the tabs). This works great, except when the activity is recreated (due to orientation changes). Here, I think the instance variables (essentially pointers to already created fragments) loose their value and are set to null. This causes the home tab to be created and be overlayed on the restored view. I also know that you can save state using the bundle passed to onSaveInstanceState and restore it using onRestoreInstanceState . But the bundle needs to contain data which is serialisable. However, these instance variables are merely pointers! How do I restore their values?

NOTE: this problem is solved below in a comment posted by me.

Thanks.

The answer to your problem is using the bundle for state restoration. Create a class in where you can put the variables and is serializable so you can put the its object to the bundle. Or you may also use SharedPreferences to store the instance variables' value in the phone storage. I hope you got idea from my weird answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM