Intent 传递Object对象类型数据

来源:互联网 发布:ubuntu怎么配置ip 编辑:程序博客网 时间:2024/06/11 02:21

对于Android来说传递基本类型数据,可以直接通过Intent传递,而对于传递复杂类型,主要是将自己的类转换为基础的字节数组,然后通过Intent实现的。 

Android序列化对象主要有两种方法,实现Serializable接口、或者实现Parcelable接口。实现Serializable接口是Java SE本身就支持的,而Parcelable是Android特有的功能,效率比实现Serializable接口高,而且还可以用在进程间通信(IPC)中。(顺便提一下:1)在使用内存的时候,Parcelable比Serializable性能高,所以推荐使用Parcelable。2)Serializable在序列化的时候会产生大量的临时变量。3)Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点,但此时还是建议使用Serializable 。)


1.实现Serializable接口非常简单,声明一下然后添加一个系列号,系统默认值便可,系统自动将对象系列化

public class Person implements Serializable {private static final long serialVersionUID = 1L;}

2.实现Parcelable接口可以从它的作用上来理解,实现了Parcelable接口的实例可以将自身的状态信息(状态信息通常指的是各成员变量的值)写入Parcel,通讯结束后从Parcel中解析其状态,一般步骤: 
1)implements Parcelable
2)重写describeContents方法,内容接口描述,默认返回0就可以
3)重写writeToParcel方法,将你的对象序列化为一个Parcel对象,即:将类的数据写入Parcel中
4)实例化静态内部对象CREATOR,这其中需重写两个方法:createFromParcel(Parcel in) 作用是从Parcel中解析数据,newArray(int size) 创建长度为size的对象数组。

简而言之:通过writeToParcel将你的对象映射成Parcel对象,再通过createFromParcel将Parcel对象映射成你的对象。也可以将Parcel看成是一个流,通过writeToParcel把对象写到流里面,在通过createFromParcel从流里读取对象,注意写成员的顺序和读成员的顺序必须一致。

例程:

MainActivity截图


SecondActivity截图



1.布局文件

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/headline"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="10dp"        android:text="MainActivity"/>    <TextView        android:id="@+id/name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/headline"        android:layout_marginLeft="30dp"        android:layout_marginTop="34dp"        android:text="姓名:"/>    <TextView        android:id="@+id/age"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/name"        android:layout_below="@+id/name"        android:layout_marginTop="30dp"        android:text="年龄:"/>    <TextView        android:id="@+id/gender"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/age"        android:layout_below="@+id/age"        android:layout_marginTop="30dp"        android:text="性别:"/>    <EditText        android:id="@+id/et_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/name"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:ems="10"/>    <EditText        android:id="@+id/et_age"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/age"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:ems="10"        android:inputType="number"/>    <EditText        android:id="@+id/et_gender"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/gender"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:ems="10"/>    <Button        android:id="@+id/btn_confirm"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/headline"        android:layout_centerVertical="true"        android:text="确定"/></RelativeLayout>

activity_second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/headline"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="10dp"        android:text="SecondActivity"/>    <TextView        android:id="@+id/name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/headline"        android:layout_marginLeft="30dp"        android:layout_marginTop="34dp"        android:text="姓名:"/>    <TextView        android:id="@+id/age"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/name"        android:layout_below="@+id/name"        android:layout_marginTop="30dp"        android:text="年龄:"/>    <TextView        android:id="@+id/gender"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/age"        android:layout_below="@+id/age"        android:layout_marginTop="30dp"        android:text="性别:"/>    <EditText        android:id="@+id/sc_et_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/name"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:editable="false"        android:ems="10"/>    <EditText        android:id="@+id/sc_et_age"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/age"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:editable="false"        android:ems="10"/>    <EditText        android:id="@+id/sc_et_gender"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/gender"        android:layout_alignParentRight="true"        android:layout_marginRight="15dp"        android:editable="false"        android:ems="10"/>    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/gender"        android:layout_marginTop="100dp"        android:layout_toRightOf="@+id/gender"        android:ems="10"        android:minLines="3"/></RelativeLayout>

2.传递的数据对象Object类,可以独立成类,在这里作为主界面的内部类

MainActivity.java

public class MainActivity extends Activity {Person person;Book book;EditText nameEditText, ageEditText, genderEditText;Button confirmButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//加载控件nameEditText = (EditText) findViewById(R.id.et_name);ageEditText = (EditText) findViewById(R.id.et_age);genderEditText = (EditText) findViewById(R.id.et_gender);confirmButton = (Button) findViewById(R.id.btn_confirm);book = new Book("家", "巴金", 33.00);//确定按钮监听从而实现启动SecondActivityconfirmButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//读取界面数据并构造一个person对象int age = Integer.parseInt(ageEditText.getText().toString());person = new Person(nameEditText.getText().toString(), age,genderEditText.getText().toString());//构造启动SecondActivity的意图对象intentIntent intent = new Intent(MainActivity.this,SecondActivity.class);//给intent添加普通类型数据//putExtra(String name, boolean value)方法的参数为键值对,name为关键字,value为想要的数值/*intent.putExtra("name", nameEditText.getText().toString());intent.putExtra("age", ageEditText.getText().toString());intent.putExtra("gender", genderEditText.getText().toString());intent.putExtra("person", person);*///这里也可以用另一种方式,先打包数据Bundle bundle = new Bundle();bundle.putSerializable("person", person);bundle.putParcelable("book", book);intent.putExtras(bundle);//把intent传递给startActivity()实现启动SecondActivitystartActivity(intent);}});}public static class Person implements Serializable {//与普通类差别的就是添加了这个系列号private static final long serialVersionUID = 1L;private String name;private int age;private String gender;public Person(String name, int age, String gender) {super();this.name = name;this.age = age;this.gender = gender;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}}public static class Book implements Parcelable {private String title;private String author;private double price;public Book(String title, String author, double price) {super();this.title = title;this.author = author;this.price = price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}//重写接口描述@Overridepublic int describeContents() {// TODO Auto-generated method stubreturn 0;}//重写方法,将对象写入parcel中,注意与读出成员的顺序@Overridepublic void writeToParcel(Parcel arg0, int arg1) {// TODO Auto-generated method stubarg0.writeString(title);arg0.writeString(author);arg0.writeDouble(price);}//实例化CREATOR,修饰符与变量名不可改public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {//解析parcel并返回对象@Overridepublic Book createFromParcel(Parcel source) {// TODO Auto-generated method stubreturn new Book(source);}@Overridepublic Book[] newArray(int size) {// TODO Auto-generated method stubreturn new Book[size];}};//从parcel中解析出对象成员public Book(Parcel source) {// TODO Auto-generated constructor stubtitle = source.readString();author = source.readString();price = source.readDouble();}}}

SecondActivity.java

public class SecondActivity extends Activity {EditText nameEditText, ageEditText, genderEditText, arrayEditText;TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_second);nameEditText = (EditText) findViewById(R.id.sc_et_name);ageEditText = (EditText) findViewById(R.id.sc_et_age);genderEditText = (EditText) findViewById(R.id.sc_et_gender);textView = (TextView) findViewById(R.id.textView);//获取intent对象Intent intent = getIntent();//获取intent携带的数据Bundle bundle = intent.getExtras();MainActivity.Person person = (MainActivity.Person) bundle.getSerializable("person");MainActivity.Book book = (MainActivity.Book) bundle.getParcelable("book");//显示到控件nameEditText.setText(person.getName());ageEditText.setText(person.getAge() + "");genderEditText.setText(person.getGender());textView.setText("《" + book.getTitle() + "》" + "\n" + book.getAuthor()+ "\n" + new DecimalFormat("##.00").format(book.getPrice()));}}

3.最后别忘了在AndroidManifest.xml 文件中添加Activity的声明:

<activity android:name=".SecondActivity"/>



0 0
原创粉丝点击