第一步:新建一个Android工程命名为ObjectTranDemo(类比较多哦!)目录结构如下图:
第二步:修改main.xml布局文件(这里我增加了两个按钮)代码如下<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome to Mr wei's blog."
/>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Serializable"
/>
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Parcelable"
/>
</LinearLayout>
第三步:新建两个类一个是Person.java实现Serializable接口,另一个Book.java实现Parcelable接口,代码分别如下:
Person.java:
1. packagecom.tutor.objecttran;
2. importjava.io.Serializable;
3. publicclassPerson implementsSerializable {
4. privatestaticfinallongserialVersionUID = -7060210544600464481L;
5. privateString name;
6. privateintage;
7. publicString getName() {
8. returnname;
9. }
10. publicvoidsetName(String name) {
11. this.name = name;
12. }
13. publicintgetAge() {
14. returnage;
15. }
16. publicvoidsetAge(intage) {
17. this.age = age;
18. }
19.
20. }
Book.java:
1. packagecom.tutor.objecttran;
2. importandroid.os.Parcel;
3. importandroid.os.Parcelable;
4. publicclassBook implementsParcelable {
5. privateString bookName;
6. privateString author;
7. privateintpublishTime;
8.
9. publicString getBookName() {
10. returnbookName;
11. }
12. publicvoidsetBookName(String bookName) {
13. this.bookName = bookName;
14. }
15. publicString getAuthor() {
16. returnauthor;
17. }
18. publicvoidsetAuthor(String author) {
19. this.author = author;
20. }
21. publicintgetPublishTime() {
22. returnpublishTime;
23. }
24. publicvoidsetPublishTime(intpublishTime) {
25. this.publishTime = publishTime;
26. }
27.
28. publicstaticfinalParcelable.Creator<Book> CREATOR = newCreator<Book>() {
29. publicBook createFromParcel(Parcel source) {
30. Book mBook = newBook();
31. mBook.bookName = source.readString();
32. mBook.author = source.readString();
33. mBook.publishTime = source.readInt();
34. returnmBook;
35. }
36. publicBook[] newArray(intsize) {
37. returnnewBook[size];
38. }
39. };
40.
41. publicintdescribeContents() {
42. return0;
43. }
44. publicvoidwriteToParcel(Parcel parcel, intflags) {
45. parcel.writeString(bookName);
46. parcel.writeString(author);
47. parcel.writeInt(publishTime);
48. }
49. }
第四步:修改ObjectTranDemo.java,并且新建两个Activity,一个是ObjectTranDemo1.java,别一个是ObjectTranDemo2.java.分别用来显示Person对像数据,和Book对象数据:,代码分别如下:
ObjectTranDemo.java: