【问题标题】:Super should be called at the end of the methodSuper 应该在方法结束时调用
【发布时间】:2017-06-10 00:02:36
【问题描述】:
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ((CustomApplication) getApplication()).detach(this);    
}

在生成 PMD 报告时,我得到了这个错误:应该在方法结束时调用 Super。通常,您最终会将超级方法保留在顶部(First Statement),以便首先调用其父类初始化。

【问题讨论】:

  • 因为调用保存实例,所以在主事件结束后如何保存个人设置?
  • 仅对构造函数是强制性的

标签: android


【解决方案1】:

通常你最终会将超级方法保持在顶部(首先 语句),以便首先调用其父类进行初始化。

以下代码 sn-p 向您展示了 Activity#onSaveInstanceState(Bundle outState) 的样子。你可以看到它只保存你通过调用super.onSaveInstanceState(outState);作为参数传入的Bundle。因此,在实际保存 Bundle 中的内容之前调用 super 方法是没有意义的。

protected void onSaveInstanceState(Bundle outState) {
    outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
    Parcelable p = mFragments.saveAllState();
    if (p != null) {
        outState.putParcelable(FRAGMENTS_TAG, p);
    }
    getApplication().dispatchActivitySaveInstanceState(this, outState);
}

【讨论】:

    【解决方案2】:

    根据这个SO,只要键不碰撞,你在哪里调用它都没有关系。它们应该是等价的。

    只要您的键不冲突(例如,ID 与 Android 内部使用的相同),两者是相同的。

    但话虽如此,谷歌关于The Activity's Lifecycle 的文档显示在最后添加了这个。不过,我仍然会遵循这一点:

    // invoked when the activity may be temporarily destroyed, save the instance state here
    @Override
    public void onSaveInstanceState(Bundle outState) {
        out.putString(GAME_STATE_KEY, mGameState);
        out.putString(TEXT_VIEW_KEY, mTextView.getText());
    
        // call superclass to save any view hierarchy
        super.onSaveInstanceState(out);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 2020-03-03
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2016-06-14
      • 2012-05-01
      • 2013-07-27
      相关资源
      最近更新 更多