当我们在活动之间来回切换时保存动态生成的视图的实例
我在单击按钮时膨胀了一个视图,用户可以添加任意数量的视图,一切都很好,我成功了,但现在的问题是,当我返回一个活动并再次回到动态生成的活动时,每个视图生成的东西消失了。如果我转到下一个活动并返回到膨胀的活动,情况也会类似。我了解 onSaveInstance
和 onRestoreSaveInstance
。但是如何将视图信息放入 onSaveInstanceState
中的捆绑包中?请注意,我的视图是动态生成的,即单击按钮时生成的,我想知道如何保留我的活动的状态。 你怎样做呢?
I am inflating a view on button click and the user can add as many views as he likes, all is fine I made it work, but now the problem is when I go back one activity and come again to my dynamically generated activity every single view that was generated is gone. Similar is the case if I go to next activity and come back to the inflated activity. I know about onSaveInstance
and onRestoreSaveInstance
. But how do I put view information in a bundle in onSaveInstanceState
? Please note that my view was generated Dynamically i.e. on button Click and I want to know as of how to preserve the state of my activity.
How do you go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您应该实现某种逻辑来帮助您恢复
Views
的状态。因此,您应该设计一个类,假设ViewDetail
以某种方式保留有关您要添加的Views
的详细信息......类型、维度等。此类应该实现Parcelable
这样您就可以添加它到捆绑包
。因此,您将保留一个
ArrayList
、myViews
,每次用户添加新的View
时,您都会创建一个新的ViewDetail
添加到myViews
数组中的 code> 对象。然后保存您的
Views
并使用这些对象恢复它们:I am thinking that you should implement some kind of logic that helps you restore the state of your
Views
. So you should be designing a class, let sayViewDetail
that somehow keeps details about theViews
that you are adding.... type, dimension, etc. This class should implementParcelable
so you are able to add it to thebundle
.So you will keep an
ArrayList<ViewDetail>
,myViews
where everytime the user adds a newView
you create a newViewDetail
object that you add to yourmyViews
array.And then save your
Views
and restore them using those objects:由于您的应用程序可能随时被完全终止,恕不另行通知,因此您必须在堆内存之外提供长期存储
。如果您的活动被终止(并且可以在任何时间),您只需恢复所有视图。终止后再次激活时,会经过onCreate()方法
- 这将是恢复活动状态的适当位置。
唯一保证在应用程序/活动被销毁之前调用的回调是 onPause() - 这是将视图状态保存到长期堆外存储的合适位置。
As your application may be killed completely at any moment without noticem you have to provide long term storage off heap memory
You only have to restore all the views, if your activity was terminated (and it can be at any time). When it is activated again after termination, it goes through onCreate() method
- this would be proper place to restore activity state.
Only callback which is guaranted to be called before your application / activity is destroyed is onPause() - this is a proper place to save views states into long term off-heap storage.