ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-10-25 17:36:51  阅读:198  来源: 互联网

标签:bundle android-intent android


这是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()更为合理.

标签:bundle,android-intent,android
来源: https://codeday.me/bug/20191025/1930227.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有