很多人会说,这有什么好说的,这基础中的基础。不过我觉得还是有必要说一下,让大家更了解一点Activity之间的传值。
先上正常情况的传值步骤
- 创建Bundle对象,并放入相应的值。
Bundle bundle = new Bundle();
bundle.putString("name","Mjj");
bundle.putInt("age",18);
- 将放好值的bundle对象绑入Intent中
intent.putExtras(bundle);
- 接收数据
Intent intent = getIntent();
String name = intent.getStringExtra("name");
看到这里,有人就会说了,不对呀,你如果是
intent.putExtra("name","ssss");
这种形式的传值,可以直接获取。如果你是使用Bundle进行了包装,你需要先使用
Bundle bundle = intent.getExtras();
获取到对应的bundle再进行值的获取。ennnnnnnnn,好吧,这个场景是我臆想的。其实这是我的疑问。所以我看了源码,明白了其中的问题所在。
Intent类中putExtra方法源码如下
public @NonNull Intent putExtra(String name, @Nullable String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
可以直观看到,我们就算没有自己包装一个Bundle,在调用putExtra的时候其实源码内部也会给我们把插入的数据放入一个bundle中。
而如果我们自己封装了bundle
public @NonNull Intent putExtras(@NonNull Bundle extras) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putAll(extras);
return this;
}
源码也是把bundle的内容全部放入这个mExtras变量中。所以我们不管是直接调用Intent的putExtra方法还是将值全部放入bundle再传值,都是一样的效果。