简体   繁体   English

重新创建活动后在Android中还原实例变量

[英]Restoring instance variables in Android upon activity recreation

I have an Android project for which I am creating a custom tab view. 我有一个要为其创建自定义标签视图的Android项目。 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. 我已经以这样一种方式来构造主ActivityFragmentActivity ),即它在屏幕底部具有一个标签栏,其上方是一个FrameLayout Each option on the tab creates a new Fragment (relating to that option). 选项卡上的每个选项都会创建一个新的Fragment (与该选项有关)。 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. 因此,当单击选项卡选项时,我检查其片段是否已创建,如果尚未创建,则将其创建并添加到FrameLayout (并隐藏所有现有片段),否则,我将隐藏现有片段(存储在名为currentlyViewedFragment的实例变量中,并显示与clicked选项匹配的已创建片段。

Also when the onCreate() of the activity is called, I set the initial tab to be the home tab (one of the tabs). 同样,在调用活动的onCreate()时,我将初始选项卡设置为主页选项卡(选项卡之一)。 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. 在这里,我认为实例变量(实际上是指向已创建片段的指针)失去了它们的值,并设置为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 . 我也知道您可以使用传递给onSaveInstanceState的捆绑包保存状态,并使用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. 或者,您也可以使用SharedPreferences将实例变量的值存储在手机存储中。 I hope you got idea from my weird answer. 希望您能从我的怪异答案中得到灵感。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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