android-为什么要在新意图的附加项中放一个新包,而不是直接在新意图中设置附加项?

android-为什么要在新意图的附加项中放一个新包,而不是直接在新意图中设置附加项?,第1张

概述这是Android的新功能,正在与老手讨论捆绑和意图.这就是我一直在做的…Intentintent=newIntent(this,TargetActivity.class).putExtra(Constants.BUNDLE_ITEM_A,itemA).putExtra(Constants.BUNDLE_ITEM_B,itemB);startActivity(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()只是一个帮助程序方法,可让您从作为方法参数接收到的捆绑包中批量设置附加项(因此而得名),因此,如果您已经有了要传递的捆绑包,则可以使用putExtras( ),但如果您自己塞东西,则使用putExtra()更为合理.

总结

以上是内存溢出为你收集整理的android-为什么要在新意图的附加项中放一个新包,而不是直接在新意图中设置附加项?全部内容,希望文章能够帮你解决android-为什么要在新意图的附加项中放一个新包,而不是直接在新意图中设置附加项?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1091684.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存