Android中Bundle类的作用
Bundle类用作携带数据,它类似于Map,用于存放key-value名值对形式的值。相对于Map,它提供了各种常用类型的putXxx()/getXxx()方法,如:putString()/getString()和putInt()/getInt(),putXxx()用于往Bundle对象放入数据,getXxx()方法用于从Bundle对象里获取数据。Bundle的内部实际上是使用了HashMap类型的变量来存放putXxx()方法放入的值。
用Bundle可以在Activity中传递基本数据类型,比如int、float、string等,但是现在的需求是如何在Activity中传递对象实例呢?就我目前所知的有两种,分别是java中Serializable和Android新引进的Parcelable方法。
我们可以考虑采用Bundle.putSerializable(Key,Object);也可以考虑采用Bundle.putParcelable(Key, Object);其中前面一种方法中的Object必须要实现Serializable接口,后面一种方法中的Object必须要实现Parcelable接口。如果没有实现这两个接口之一,那么我们可以使用Bundle.putSerializable(Key,Object)或者Bundle.putParcelable(Key, Object),但起不到任何作用,下面我们以一个完整的例子来说明。
1.新建一个Android的工程,其中该工程的目录结构如下图:
2. 修改main.xml布局文件。布局文件的源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
3.在工程的src目录下新建一个实体类包,命名为com.andy.entity.同时在该package中添加两个实体类,一个是Person.java,该类实现Serializable接口;一个是Police.java,该类实现Parcelable接口。代码分别如下:
Person.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Police.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
4.在包com.andy.testdemo中修改TestActivity.java类,同时在该包中添加类SerializableDemo和ParcelableDemo,分别继承了Activity类和分别显示Person对象和Police对象的数据。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
|
SerializableDemo.java类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
ParcelableDemo.java类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
5.在AndroidManifest.xml文件中为新添加的两个Activity进行注册。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|