搬家网站建设公司,西安是哪个省市,做竞价推广的网站要求,网站建设海淀一、前言
这篇文章主要针对Serialiable和Parcelable接口来传递对象。呈现的功能是跳转到另一个界面#xff0c;然后通过toast展现我收到的数据。
二、使用Serialiable接口传递数据
1.创建需要传递的对象
//必须实现Serializable接口#xff0c;此对象才有传递的资格
publ…一、前言
这篇文章主要针对Serialiable和Parcelable接口来传递对象。呈现的功能是跳转到另一个界面然后通过toast展现我收到的数据。
二、使用Serialiable接口传递数据
1.创建需要传递的对象
//必须实现Serializable接口此对象才有传递的资格
public class Student implements Serializable {public int id;public String name;public int age;}2.传数据 /*** 跳转到Serialiable2Activity* param view*/public void startActivity(View view) {Intent intent new Intent(this, Serialiable2Activity.class);//传递对象到Serialiable2ActivityStudent student new Student();student.id 9;student.name Anglin;student.age 33;intent.putExtra(student,student);startActivity(intent);}
3.接收数据
Intent intent getIntent();Student student (Student) intent.getSerializableExtra(student);//提示显示Toast.makeText(this, student.id student.id student.namestudent.name student.age student.age,Toast.LENGTH_SHORT).show();
二、使用Parcelable接口传递数据
1.创建需要传递的数据对象
//成为Parcelable的子类就具备传递数据的资格
public class ParcelableStudent implements Parcelable {public ParcelableStudent() {}//我们自己定义的成员public String name;public int age;//TODO 读取的数据和写入的数据一定要一致否则会报错//从Parcel对象里面读出来赋值给成员//构造函数protected ParcelableStudent(Parcel in) {//这个函数的意义就是从Parcel读取数据赋值给name和agename in.readString();age in.readInt();}//把属性写入到Parcel 对象中去Overridepublic void writeToParcel(NonNull Parcel parcel, int i) {parcel.writeString(name);parcel.writeInt(age);}//先不管是系统扩展用的Overridepublic int describeContents() {return 0;}//静态公开的成员Parcelable内部会调用。 一定要有 自动生成 或者从文档中复制不需要去写。public static final CreatorParcelableStudent CREATOR new CreatorParcelableStudent() {//创建ParcelableStudent对象 并且Parcel对象构建好传递给ParcelableStudent成员数据就可以从Parcel获取了Overridepublic ParcelableStudent createFromParcel(Parcel in) {return new ParcelableStudent(in);}//Overridepublic ParcelableStudent[] newArray(int size) {return new ParcelableStudent[size];}};
}
2.传送数据 public void startActivity(View view) {Intent intent new Intent(this,Parcelable2Activity.class);ParcelableStudent student new ParcelableStudent();student.age 20;student.name Anglin;intent.putExtra(student,student);startActivity(intent);}
3.接收数据 Intent intent getIntent();ParcelableStudent student intent.getParcelableExtra(student);//显示Parcelable1Activity 传递过来的对象 里面的数据Toast.makeText(this, student.name student.name student.age student.age, Toast.LENGTH_SHORT).show();
四、总结
那么在编写android代码 的时候这两个我们改选择使用哪个呢一般我们会选择使用Parcelabe因为parcelable的性能更高。Serialiable面向jvm使用java序列化的形式传递对象的。android平台的虚拟机更适合Parcelable。
所以android开发必须使用Parcelabe因为这个是支持 兼容安卓虚拟机。我们主推的方式