Bundle 翻译成中文的意思是“捆绑”,常用在Activity间传递参数,之前一开始并不太待见,原因是Intent本身就可以传递,Intent.putExtra("key", value),为何还要用Bundle呢?
先看Intent用法:
Intent intent = new Intent();
intent.putExtra("key1", value1);
intent.putExtra("key2", value2);
在看Bundle 用法:
Bundle bundle = new Bundle();
bundle.putString("key1", value1);
bundle.putString("key2", value2);
intent.putExtras(bundle);
取值操作:
Bundle bundle = this.getIntent().getExtras();
String v = bundle.getString("key1");
例如:我现在要从A界面,跳转到B界面或者C界面,这样的话 我就需要写2个Intent 。但是如果你还要涉及的传值的话,你的Intent就要写两遍添加值的方法,如果我用1个Bundle 直接把值先存里边 然后再存到Intent中 不就更简洁吗?
另外一个例子 如果我现在有 Activity A ,B ,C;
现在我要把值通过A经过B传给C,你怎么传 如果用Intent的话, A-B先写一遍,再在B中都取出来 然后在把值塞到Intent中再跳到C,累吗?
如果我在A中用了 Bundle 的话,我把Bundle传给B,在B中再转传到C ,C就可以直接去了 ,这样的话 还有一个好处,就是在B中,还可以给Bundle对象添加新的 key - value ,同样可以在C中取出来。
如果仅从这点看,还不足以看出Bundle的特别之处,我们知道Intent 传递参数是有类型限制的,例如String ,int ,float等,它是不能传递对象的,那么Bundle可以么?答案是可以的,不难发现Bundle 中有一个方法putSerializable,利用该对象就可以传递对象了,不过传递的对象要实现Serializable接口,例如传递User类的对象:
User 类
public class User implements Serializable {
//其他代码省略
}
关键代码
User user = new User();
Intent intent = new Intent(MyActivity.this,OthereActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("user", user);
intent.putExtras(bundle);
startActivity(intent);
接受对象方法同其他类似。