在Activity中使用方法:
1)传递单一对象,具体代码如下:
// parcelable对象传递方法
java序列化的作用?public void setParcelableMethod() {
Person person = new Person();
person.setmName("王海康");
person.setmSex("男");
Android原生?person.setmAge(45);
Intent intent = new Intent(this, PersonTest.class);
Bundle bundle = new Bundle();
bundle.putParcelable(PAR_KEY, person);
java序列化原理,intent.putExtras(bundle);
startActivity(intent);
}
// parcelable对象获取方法
序列化的作用、public Person getParcelableMethod(){
Person mPerson = (Person)getIntent().getParcelableExtra(PAR_KEY);
return mPerson;
}
android序列化。2)传递对象列表,具体代码如下:
需要注意的是,若ListpersonList = new ArrayList();则会报错,因为下面调用的putParcelableArrayList()函数其中一个参数的类型为ArrayList。
// parcelable对象List传递方法
public void setParcelableListMethod() {
android技术,ArrayList personList = new ArrayList();
Person person1 = new Person();
person1.setmName("王海康");
person1.setmSex("男");
序列化的作用和应用场景?person1.setmAge(45);
personList.add(person1);
Person person2 = new Person();
person2.setmName("薛岳");
person2.setmSex("男");
person2.setmAge(15);
personList.add(person2);
Intent intent = new Intent(this, PersonTest.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(PAR_LIST_KEY, personList);
intent.putExtras(bundle);
startActivity(intent);
}
// parcelable对象获取方法
public ArrayList getParcelableMethod(){
ArrayList mPersonList = getIntent().getParcelableExtra(PAR_LIST_KEY);
return mPersonList;
}
3)最后介绍一个投机取巧的方法:
不用继承Parcelable或Serializable方法即可实现IPC中对象的传递。这种方法的实现原理不是很明白,只知道代码中new ArrayList()返回的其实是一个EmptyArray.OBJECT数组,不过我感觉应该还是系统调用Serializable进行序列化的,如果各位读者有好的想法,欢迎告知。
具体代码如下:
//对象List传递
public void setObjectMethod(){
......(省略)
ArrayList list = new ArrayList();
//ObjectList为某一对象列表
list.add(ObjectList);
bundle.putParcelableArrayList(PAR_LIST_KEY, list);
intent.putExtras(bundle);
startActivity(intent);
}
//获取对象List
ArrayList list = bundle.getParcelableArrayList("list");
//强转成你自己定义的list,这样ObjectList就是你传过来的那个list了。
ObjectList= (List) list.get(0);
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态