使用Intent传递对象
在Android开发中使用Intent可以用来启动活动、发送广播、等等。。。
我们还可以在Intent中添加一些附加数据,已达到传值的效果,
比如在First Activity中添加以下代码:
Intent
intent =
new
Intent
()
;
intent.putExtra(
"string_data"
,
"hello"
)
;
intent.putExtra(
"int_data"
,
100
)
;
startActivity(intent)
;
之后就可以在SecondActivity中得到这些值了,代码如下:
getIntent().getStringExtra("string_data"); getIntent().getIntExtra("int_data",0);
但是putExtra()方法所支持的数据类型是有限的,虽然常用的一些类型是有限的,但是当你想传递一些自定义的对象时,就会发现无从下手
所以我们就该学习一下使用Intent来传递对象的技巧
1.使用Serializable
Serializable是序列化的意思,表示将一个对象转化成可储存或者可传输的状态,只需要让一个类去实现Serializable这个接口就可以了,代码如下:
package com.example.lab.android.nuc.uibestpractice; import java.io.Serializable; public class Person implements Serializable { private String name; private int age; 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; } }
接下来在FirstActivity中的代码也非常简单:
Person person = new Person(); person.setName("wanghao"); person.setAge(18); Intent intent = new Intent(MainActivity.this,SecondActivity.class); intent.putExtra("person_data",person); startActivity(intent);
接下来在SecondActivity中获取这个对象也很简单:
Person person = (Person) getIntent().getSerializableExtra("person_data");
2.使用Parcelable
除了Serializable之外,使用Parcelable可以实现相同的效果,不过不同于将对象序列化,Parcelable方式的原理是讲一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的类型,代码如下:
package com.example.lab.android.nuc.uibestpractice; import android.os.Parcel; import android.os.Parcelable; public class People implements Parcelable { private String name; private int age; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name);//写出name dest.writeInt(age);//写出age } public static final Parcelable.Creator<People> CREATOR = new Parcelable.Creator<People>(){ @Override public People createFromParcel(Parcel source) { People people = new People(); // 读取的顺序一定要和上面的一样 people.name = source.readString();//读取姓名 people.age = source.readInt();//读取年龄 return people; } @Override public People[] newArray(int size) { return new People[size]; } }; }
首先我们让People类去实现了Parcelable接口,这样就必须重写describeContents()和writeToParcel()这两个方法,其中describeContents()方法直接返回0就可以了,而writeToParcel()我们需要调用Parcel的writeXxx()方法,将People类的字段一一写出。
除此之外,我们还必须在People类中提供一个名为CREATOR的常量,这里创建了一个Parcelable.Creator接口的一个实现,并将泛型指定为People,接着要重写createFromParcel()和呢我Array()这两个方法,在createFromParcel()方法里面我们要读取刚才的字段,并创建一个对象进行返回。
在FirstActivity中我们仍然可以使用相同的代码来传递People对象,只不过在SecondACtivity中获取对象的时候稍作修改:
Person person = (Person) getIntent().getParcelableExtra("person_data");