Android,保持视图
我的应用程序包含两部分:网络部分和 GUI。它的工作方式有点像浏览器 - 用户从服务器请求一些信息,服务器发回一些代表某些视图的数据,然后 GUI 显示它。
现在我已经将网络部分实现为服务,它自行构建和保存所有视图。创建活动时,网络部分将其内容视图设置为最后接收到的视图。
这非常简单,不需要重新创建所有视图层次结构并保存所有状态。
但有一个问题 - 我可以在服务上下文中创建视图,我可以在活动启动之间保留它们,可以在销毁和创建活动时取消绑定和重新绑定视图吗?但某些视图需要 Activity 上下文(例如 Spinner,它创建弹出对话框)。
那么,有什么方法可以在创建视图后更改视图的上下文吗?
我对android编程很陌生,所以可能有一些更好的方法来做到这一点(同样,任务是 - 例如,当活动被破坏和重新创建时,当屏幕旋转发生时,保留视图层次结构和所有状态)。
My application contains 2 parts: a network part and GUI. It works kinda like a browser - user requests some information from server, server sends back some data representing some view, then GUI displays it.
Right now I've implemented network part as a service, which constructs and keeps all the views by itself. When an activity is created, network part sets it's content view to the last received view.
That's pretty simple, no need to recreate all the view hierarchy and saving all the states.
But there is problem - I can create Views within service context, I can keep them between activity launches, can unbind and rebind views when an activity is destroyed and created? but some views require Activity context (e.g. Spinner, that creates popup dialog).
So, is there any way to change context of a View after creation?
I'm very new in android programming, so there may be some better way to do this (again, the task is - keep view hierarchy and all the states when activity beeing destroyed and recreated, when a screen rotating occurs, for example).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我坚信您的做法是错误的:“我已将网络部分实现为服务,它自行构建并保留所有视图。”。
Activity
仅用于拥有/管理视图层次结构。因此,Activity
应该向Service
请求(或以某种方式由Service
通知)要显示的数据,然后更新其视图。是的,在某些情况下它需要状态管理,但你得到的好处是 - 它只是按预期工作,没有任何黑客攻击。换句话说 - 不要试图欺骗操作系统,而是尝试符合 Android 的最佳实践。I strongly believe you are on the wrong way with "I've implemented network part as a service, which constructs and keeps all the views by itself.".
It is the
Activity
only that is intended to have/manage Views hierarchy. So anActivity
should ask aService
(or be somehow notified by theService
) for the data to display and then just update its views. Yes, in some cases it requires state management, but the benefit you get - it just works as intended without any hacks. In other words - don't try to cheat the OS, instead try to correspond to the best practices for Android.