【问题标题】:Android activity life cycle: why isn't calling the super method first enforced?Android活动生命周期:为什么不首先强制调用超级方法?
【发布时间】:2014-06-17 17:24:51
【问题描述】:

基本 Android 开发的要求之一(根据 Google 文档)是,当您覆盖 Activity 的生命周期方法(onCreate、onResume、onPause 等)时,您必须首先调用父级的方法:

@Override
protected void onResume()
{
    super.onResume();
}

为什么 Android API 不使用非虚拟接口模式来强制执行此行为,而不是依靠开发人员记住这样做?:

Android 的 Activity Base 类可能如下所示(粗略示例):

public class Activity
{
    public final void onResume()
    {
        // do important things here
        virtualOnResume();   
    }
    protected abstract void virtualOnResume();
}

Android 开发者编写的子类:

public class MainActivity extends Activity
{
    @Override
    protected void virtualOnResume()
    {
        // do custom stuff here, without needing to call super.onResume()
    }
}

我还没有遇到过需要在调用 super 方法之前编写任何指令的情况。有没有什么时候我们不应该调用超级方法,或者不先调用它?如果对于生命周期中的任何特定方法,它确实必须始终处于首位,那么设计决定不使用 NVI 模式来执行它的原因是什么?

更新:现在已经为 Android 开发了一段时间,工作中的每个人都使用我的 BaseActivity NVI 类,但我仍然没有遇到不为所有生命周期方法使用 NVI 的理由,但是onCreate 一个。似乎那些为现有 API 设计辩护/评论的人并没有真正的理由,或者似乎并不真正理解 NVI 模式是什么,所以我假设没有好的原因,它“就是这样”。

【问题讨论】:

  • 您不必致电super.onResume();,只需在Activity 中致电super.onCreate(...)。除此之外,您可以完全覆盖任何方法。
  • Google 文档明确表示始终在所有生命周期方法上调用超级方法。无论如何,即使它只是 onCreate 方法,同样的问题仍然存在:为什么不使用 NVI 呢?
  • 您能否链接到说明这一点的文档部分?因为只有onCreate() 才需要。如果你没有在onCreate() 中调用super.onCreate(),就会抛出异常。
  • Google's Android Developer section 中,它说:您对这些生命周期方法的实现必须始终在执行任何工作之前调用超类实现

标签: java android android-activity non-virtual-interface


【解决方案1】:

您不必调用超级方法作为方法的第一条语句。有时你可能想在调用 super 方法之前和之后做一些事情。

例如见FragmentActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    mFragments.attachActivity(this, mContainer, null);
    // Old versions of the platform didn't do this!
    if (getLayoutInflater().getFactory() == null) {
        getLayoutInflater().setFactory(this);
    }

    super.onCreate(savedInstanceState);

    NonConfigurationInstances nc = (NonConfigurationInstances)
            getLastNonConfigurationInstance();
    if (nc != null) {
        mAllLoaderManagers = nc.loaders;
    }
    if (savedInstanceState != null) {
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
    }
    mFragments.dispatchCreate();
}

【讨论】:

  • 好答案。这显然违背了他们在文档中的建议。所有其他生命周期方法是否也存在这种情况?
【解决方案2】:

这是一种 API 设计选择。它使 API 表面更小(更少的方法)并且是标准模式 (http://en.wikipedia.org/wiki/Decorator_pattern)。

【讨论】:

猜你喜欢
  • 2013-05-01
  • 1970-01-01
  • 2017-03-14
  • 2012-01-20
  • 2013-01-13
  • 2011-12-18
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
相关资源
最近更新 更多