需要合适的Android模式
我正在开发一个 Android 应用程序,并面临重构问题;我的大部分活动都需要某些通知功能,即显示 Toast 消息。这是由扩展 Activity
Activity
-NotificationActivity
--MyActivityA
--MyActivityB
等的超类处理的。然后,我决定重构两个使用由数据库游标填充的 Spinner 的活动。层次结构现在看起来像这样:
Activity
-MyNotificationActivity
--MyActivityA
--MyActivityB
--MySpinnerActivity (设置 Spinner 和 Cursor)
---MySpinnerActivityA
---MySpinnerActivityB
我现在面临的问题是这样的 - 我正在编写一个新的 Activity 类它还将使用数据库 Cursor,但填充 ListView。我想扩展 ListView 以利用内置的 Android 列表管理,但我还需要访问 Cursor 设置方法和通知方法,这些方法已经存在于我的类层次结构中。
我真的很想避免代码重复。有什么建议吗?
干杯, 巴里
I'm working on an Android application and am faced with a refactoring issue; most of my activities need certain notification abilities, i.e. showing a Toast message. This is handled by a superclass which extends Activity
Activity
-NotificationActivity
--MyActivityA
--MyActivityB
and so on. I then decided to refactor two of my activities which make use of a Spinner which is populated by a database cursor. The hierarchy now looks like this:
Activity
-MyNotificationActivity
--MyActivityA
--MyActivityB
--MySpinnerActivity (sets up Spinner and Cursor)
---MySpinnerActivityA
---MySpinnerActivityB
The problem I am facing now is this - I am writing a new Activity class which will also make use of a database Cursor but to populate a ListView. I would like to extend ListView to make use of built in Android List management, but I also need access to the Cursor set up methods and Notification methods, which already exist in my class hierarchy.
I'm really keen to avoid code dupication. Any suggestions?
Cheers,
Barry
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在处理类似的问题(一堆显示 ProgressDialogs 的活动)时,我避免使用 ProgressDialog 功能扩展超类。
相反,我编写了一个单独的类“LoadingDialog”来处理它。在需要此功能的每个活动中,它将有一个 LoadingDialog 类的实例作为字段。并且,对于任何依赖于上下文或活动的功能,活动可以传递对其自身的引用,或根据需要公开其自身的其他部分。
在您的情况下,也许您可以编写某种“ToasterFunctionClass”来封装常见功能,并在每个适当的活动中拥有它的实例。
In dealing with a similar issue (a bunch of activities which show ProgressDialogs), I avoided extending a superclass with the ProgressDialog functionality.
Instead, I wrote a separate class, "LoadingDialog", to handle it. In each Activity that needed this functionality, it would have an instance of class LoadingDialog as a field. And, for any Context- or Activity-dependent functionality, the Activity could pass a reference to itself, or expose other bits of itself as needed.
In your case, perhaps you could write some kind of "ToasterFunctionClass" which encapsulates the common functionality, and have an instance of it in each of the appropriate Activities.