在开发中不少要用到Activity直接传输对象,下面我们来看看,其实跟java里面差不多
自定义对象的传递:通过intent传递自定义对象的方法有两个
第一是实现Serialization接口;
第二是实现Parcelable接口;
下面来看个例子:
package com.example.bean; import java.io.Serializable; public class Bed implements Serializable { private String name; private int number; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public String toString() { return "Name:" + getName() + ",Number:" + getNumber(); } }
package com.example.bean; import android.os.Parcel; import android.os.Parcelable; public class Patient implements Parcelable { private String name; private int number; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public static final Parcelable.Creator<Patient> CREATOR = new Parcelable.Creator<Patient>() { public Patient createFromParcel(Parcel p) { Patient patient = new Patient(); patient.name = p.readString(); patient.number = p.readInt(); return patient; } public Patient[] newArray(int size) { return new Patient[size]; } }; @Override public int describeContents() { return 0; } /** * *@desc 注:这里的write方法和createFromParcel里的一一对应,不然createFromParcel都是p.readString(),你怎么知道是哪一个 * */ @Override public void writeToParcel(Parcel p, int flags) { p.writeString(name); p.writeInt(number); } @Override public String toString() { return "Name:" + getName() + ",Number:" + getNumber(); } }
TestActivity.java: StringBuilder sb = new StringBuilder(); sb.append("Serializable Bed对象\n"); Bed bed = (Bed) getIntent().getExtras().get("bed"); sb.append(bed.toString()); sb.append("\n\nList<Serializable Bed>集合\n"); List<Bed> listBed = (List<Bed>) getIntent() .getSerializableExtra("beds"); for (int i = 0; i < listBed.size(); i++) { sb.append(listBed.get(i).toString() + ";"); } sb.append("\n\nParcelable Patient对象\n"); Patient patient = getIntent().getParcelableExtra("patient1"); sb.append(patient.toString()); sb.append("\n\nParcelable Patient byte[]\n"); byte[] data = getIntent().getByteArrayExtra("patient2"); if (data != null) { Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); patient = Patient.CREATOR.createFromParcel(in); } sb.append(patient.toString()); sb.append("\n\nString数组\n"); String[] str = getIntent().getStringArrayExtra("patients"); for (int i = 0; i < str.length; i++) { sb.append(str[i]); } TextView tv = (TextView) findViewById(R.id.tv); tv.setText(sb);
时间: 2024-10-17 12:15:44