为什么要将新捆绑包放入新意图的 extras 中,而不是直接在新意图上设置 extras ?

Why would you put a new bundle in a new intent's extras vs setting extras directly on the new intent?

这里是 Android 的新手,我正在与一位老手就捆绑包和意图进行辩论。这就是我一直在做的...

Intent intent = new Intent(this, TargetActivity.class)
    .putExtra(Constants.BUNDLE_ITEM_A, itemA)
    .putExtra(Constants.BUNDLE_ITEM_B, itemB);

startActivity(intent);

他说那是错误的,你应该显式地创建一个新包,然后将它传递给 'putExtras',像这样...

Intent intent = new Intent(this, TargetActivity.class);

Bundle bundle = new Bundle();
bundle.putSerializable(Constants.BUNDLE_ITEM_A, itemA);
bundle.putSerializable(Constants.BUNDLE_ITEM_B, itemB);
intent.putExtras(bundle);

startActivity(intent);

但是,'putExtras' 已经在内部创建了一个新的包,然后只是合并到传入的包中,本质上意味着它是一个一次性对象(对于这个用例)。这是 'putExtras'...

的来源
public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

...所以看起来他的方法是多余的,而且实际上是浪费的,因为它创建了一个不必要的包分配,只是为了将它拆开并与已经在意图中的那个合并。

所以我错过了什么吗?按照他的建议进行操作是否有技术原因?

Note: I understand using 'putExtras' to pass around bundles that were handed to you. This however is creating a new bundle simply to insert in a new intent so it seems unnecessary to me, but I could be wrong. That's why I'm asking about technical benefits to his approach.

That's why I'm asking about technical benefits to his approach.

TL;TR:您所说的情况没有任何好处。反了

调用 putExtra() 错误是相当愚蠢的,并且充分暴露了对 Intent 内部知识的缺乏。你的老手应该快速看一下 Intent.java sources 而不是盲目争论,因为他会清楚地看到:

public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

putAll()在做什么? Docs 说:

Inserts all mappings from the given Bundle into this Bundle.

因此 putExtras() 只是将作为参数给出的 Bundle 中的所有映射插入到 Intent 的内部包中。

在这一点上很明显,手动创建单独的 Bundle,然后将所有额外内容塞入其中只是为了将该 bundle 传递给 putExtras() 与直接填充一堆 putExtra() 相比,带来的好处完全为零来电。

putExtras() 只是一个辅助方法,可以让您从作为方法参数收到的 bundle 中批量设置附加值(因此得名),因此如果您手头已经有一个要传递的 bundle一直以来,你会 putExtras(),但如果你自己填充东西,使用 putExtra() 更有意义。