Can I create a single class which can be the parent for every type of Activity?
I wish to have a single class which all of my Activity
classes extend. I have ListActivities
, Activities
, MapActivities
, TabActivities
, etc in my App.
I have many of these different activities in my app, ~12 activities. I want each of them to have the methods which are in the parent class.
Right now, i have created 4 parent activ开发者_如何学Goity classes which are extended from a certain activity depending on their type(ListActivity
, Activity
, MapActivity
, TabActivity
)
I am creating a lot of redundant code - each of the 4 parent activities has almost identical code, in exception for what class activity it extends.
Here is an example that may clarify what my problem is:
- I have an
Activity
:MenuScreen
which extendsBaseListActivity
BaseListActivity
extendsListActivity
BaseListActivity
contains methods and fields which i want all my activities to have access toI have another
Activity
:HomeScreen
which extendsBaseActivity
BaseActivity
extendsActivity
BaseActivity
contains the same methods and fields which are in my otherBase[<type>]Activity
classes(such asBaseListActivity
)
these methods/fields are copy-pasted to all my Base[<type>]Activity
, and seems awfully redundant to me.
Can i create a master activity class which all types of Activity classes can use as its parent? if not, am i stuck with copy and pasting this code and feeling gross/dirty about it?
Can i create a master activity class which all types of Activity classes can use as its parent?
No, sorry.
if not, am i stuck with copy and pasting this code and feeling gross/dirty about it?
First, you do not need ListActivity
or TabActivity
. You do not need ListActivity
for a ListView
; you do not need TabActivity
for a TabHost
. That knocks things down to two base classes: Activity
and MapActivity
. Unfortunately, you do need to extend MapActivity
to use MapView
.
For that, you can use composition to minimize redundancy. Rather than your "methods and fields which i want all my activities to have access to" being implemented on the activity, implement them on some other object, and have BaseActivity
and BaseMapActivity
hold onto an instance of that object. You will still need some amount of duplicate code (e.g., for lifecycle methods like onStop()
), but more stuff can be located in a single class.
Yes, you can make a master class, that has all the redundant code. Although the problem is, that you use ListActivities, TabActivites and so on, which are only convenience classes (they extends the Activity class and do some chores for you, but not that much).
I'd just ditch them, make a class named BaseActivity that extends the Activity class, and has all the redundant code parts. Then, all your activites should extends BaseActivity.
精彩评论