When do I need a base activity and base fragment?

2020-07-18 07:05发布

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?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-18 07:23

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)

查看更多
对你真心纯属浪费
3楼-- · 2020-07-18 07:23

When we need Global error handling we can use base activity/fragment.

查看更多
戒情不戒烟
4楼-- · 2020-07-18 07:34

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);
查看更多
登录 后发表回答