In lot of examples I see, all the activities and fragments extends from base activity and base fragments. 2 questions:
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 calling setContentView
. So it's better if you create a base activity and extend the setContentView
method in it like this:
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
}
In child activities when you call setContentView
at the beginning of onCreate
(after calling super.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:
startActivity(new Intent(this, NextActivity.class));
You can add a start
method to your base activity like this:
protected void start(Class<? extends BaseActivity> activity) {
startActivity(new Intent(this, activity));
}
and start the next activity like:
start(NextActivity.class);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With