在Android开发中,有时候需要从一个Activity中传递数据到另一个Activity中,在Bundle中已经封装好了简单数据类型,例如String ,int ,float等。但是如果我们想要传递一个复杂的数据类型,比如一个Book对象,该怎么办呢?
仔细的看了一下Bundle中的方法,其中有一个是putSerializable()方法,Serializable对象是一个可恢复对象接口,我们只需要让Book对象实现Serializable接口,就可以使用Bundle.putSerializable()方法传递Book对象了。废话不多说了,现将代码贴上:
Book类:
package com.bundletest.model.fneg; import java.io.Serializable; /** *@Copyright:Copyright (c) 2008 - 2100 *@Company:Sagret *@Author:fengcunhan fengcunhan@gmail.com *@Package:com.bundletest.model.fneg *@FileName:Book.java *@Time:2010-12-19 *@User:feng */
public class Book implements Serializable { private static final long serialVersionUID = 1L; private String name; private String id; private String author;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; } }
实例化Book类,得到Book对象book以及设置成员变量:
if(TextUtils.isEmpty(bookName)||TextUtils.isEmpty(author)||TextUtils.isEmpty(id)){ Toast.makeText(AndroidBundleActivity.this, "输入框不能为空", Toast.LENGTH_SHORT).show(); }else{ Book book=new Book(); book.setName(bookName); book.setAuthor(author); book.setId(id);
Intent intent=new Intent(AndroidBundleActivity.this,RecieveActivity.class); Bundle bundle=new Bundle(); bundle.putSerializable("book", book); intent.putExtras(bundle);
startActivity(intent); }
在另一个Activity中获取传递过来的book对象,并显示:
Intent intent=this.getIntent(); Bundle bundle=intent.getExtras(); Book book=(Book)bundle.getSerializable("book"); nameText.setText("书名:"+book.getName()); authorText.setText("作者:"+book.getAuthor()); idText.setText("ID:"+book.getId());