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 activity 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:MenuScreenwhich extendsBaseListActivity BaseListActivityextendsListActivity-
BaseListActivitycontains methods and fields which i want all my activities to have access to -
I have another
Activity:HomeScreenwhich extendsBaseActivity BaseActivityextendsActivityBaseActivitycontains the same methods and fields which are in my otherBase[<type>]Activityclasses(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?
No, sorry.
First, you do not need
ListActivityorTabActivity. You do not needListActivityfor aListView; you do not needTabActivityfor aTabHost. That knocks things down to two base classes:ActivityandMapActivity. Unfortunately, you do need to extendMapActivityto useMapView.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
BaseActivityandBaseMapActivityhold onto an instance of that object. You will still need some amount of duplicate code (e.g., for lifecycle methods likeonStop()), but more stuff can be located in a single class.