When do I need a base activity and base fragment?

空扰寡人 提交于 2020-01-13 19:48:03

问题


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?

回答1:


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);



回答2:


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:


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



来源:https://stackoverflow.com/questions/32552592/when-do-i-need-a-base-activity-and-base-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!