Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need a base activity and base fragment?

In lot of examples I see, all the activities and fragments extends from base activity and base fragments. 2 questions:

  1. When should I use it?
  2. What kind of code should go in it?
like image 626
T_C Avatar asked Sep 13 '15 17:09

T_C


Video Answer


2 Answers

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);
like image 128
Ashkan Sarlak Avatar answered Sep 18 '22 20:09

Ashkan Sarlak


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)

like image 42
ivan.panasiuk Avatar answered Sep 21 '22 20:09

ivan.panasiuk