我什么时候需要基础活动和基础片段? [英] When do I need a base activity and base fragment?

查看:81
本文介绍了我什么时候需要基础活动和基础片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多示例中,我看到所有活动和片段都来自基本活动和基本片段. 2个问题:

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

  1. 我什么时候应该使用它?
  2. 应该放入哪种代码?

推荐答案

通常,当我需要在所有活动"/片段"的生命周期回调中进行某些工作时,我会使用基本的活动/片段".

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.

例如,如果您使用黄油刀(非常推荐),则需要致电Butterknife.bind(Activity a)调用setContentView之后.因此,最好创建一个基本活动并像这样扩展setContentView方法:

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

在子活动中,当您在onCreate的开头(在调用super.onCreate之后)调用setContentView时,会自动调用ButterKnife.bind.

In child activities when you call setContentView at the beginning of onCreate (after calling super.onCreate), ButterKnife.bind would be called automatically.

另一个用例是当您要实现一些辅助方法时.例如,如果您在活动中多次呼叫startActivity,那将是非常头痛的事情:

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

您可以将start方法添加到基本活动中,如下所示:

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

这篇关于我什么时候需要基础活动和基础片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆