In lot of examples I see, all the activities and fragments extends from base activity and base fragments. 2 questions:
- When should I use it?
- What kind of code should go in it?
In lot of examples I see, all the activities and fragments extends from base activity and base fragments. 2 questions:
Other activities can extend BaseActivity. If you define common elements in BaseActivities and all other activities extend BaseActivities, then all activities will have these common elements, for example: custom menu, custom bar, design layout or some query logic...etc.
Similar with BaseFragment. I usually log onCreate, onAtach, onPause events in BaseFragment. So I see these logs in all other Fragment that extend BaseFragment. Also, you can very easy and in one class turn-off these logs for all fragment. (useful before publishing realise)
When we need Global error handling we can use base activity/fragment.
Usually I use a base Activity/Fragment when I need to do some work in some of life-cycle callbacks of all of my Activitys/Fragments.
For example if you use Butter Knife (very recommended), you need to call
Butterknife.bind(Activity a)
after callingsetContentView
. So it's better if you create a base activity and extend thesetContentView
method in it like this:In child activities when you call
setContentView
at the beginning ofonCreate
(after callingsuper.onCreate
),ButterKnife.bind
would be called automatically.Another use case is when you want to implement some helper methods. For example if you are calling
startActivity
multiple times in your activities, this would be a real headache:You can add a
start
method to your base activity like this:and start the next activity like: