Android学习札记14:利用Parcelable在Activity间传递复杂的嵌套ArrayList对象参数

public class Menu implements Parcelable {

	private int id;
	private String name;
	
	
	public Menu() {
		
	}
	
	
	public Menu(Parcel source) {
		id = source.readInt();
		name = source.readString();
	}
	
	
	public int getId() {
		return id;
	}
	
	
	public void setId(int id) {
		this.id = id;
	}
	
	
	public String getName() {
		return name;
	}
	
	
	public void setName(String name) {
		this.name = name;
	}


	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeInt(id);
		dest.writeString(name);
	}
	
	
	public static final Parcelable.Creator<Menu> CREATOR = new Creator<Menu>() {

		@Override
		public Menu createFromParcel(Parcel source) {
			// TODO Auto-generated method stub
			return new Menu(source);
		}

		@Override
		public Menu[] newArray(int size) {
			// TODO Auto-generated method stub
			return new Menu[size];
		}
		
	};
	
}



public class Shop implements Parcelable {

	private int id;
	private String name;
	private String tel;
	private ArrayList<Menu> menu_AList;
	
	
	public Shop() {
		
	}
	
	
	public Shop(Parcel source) {
		id = source.readInt();
		name = source.readString();
		tel = source.readString();

		menu_AList = new ArrayList<Menu>();
		source.readTypedList(menu_AList, Menu.CREATOR);
	}
	
	
	public int getId() {
		return id;
	}
	
	
	public void setId(int id) {
		this.id = id;
	}
	
	
	public String getName() {
		return name;
	}
	
	
	public void setName(String name) {
		this.name = name;
	}
	
	
	public String getTel() {
		return tel;
	}
	
	
	public void setTel(String tel) {
		this.tel = tel;
	}
	
	
	public ArrayList<Menu> getMenuAList() {
		return menu_AList;
	}
	
	
	public void setMenuAList(ArrayList<Menu> menu_AList) {
		this.menu_AList = menu_AList;
	}


	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeInt(id);
		dest.writeString(name);
		dest.writeString(tel);

		dest.writeTypedList(menu_AList);
	}
	
	
	public static final Parcelable.Creator<Shop> CREATOR = new Creator<Shop>() {

		@Override
		public Shop createFromParcel(Parcel source) {
			// TODO Auto-generated method stub			
			return new Shop(source);
		}

		@Override
		public Shop[] newArray(int size) {
			// TODO Auto-generated method stub
			return new Shop[size];
		}
		
	};
}



最关键的代码是这段:

		menu_AList = new ArrayList<Menu>();
		source.readTypedList(menu_AList, Menu.CREATOR);

Shop类调用嵌套的Menu类的CREATOR来读取数据,进而生成ArrayList<Menu>。

另外,如果在Menu类中再嵌套其他类,这个时候就会发现跳转Activity传递数据时速度就下降了很多。

所以,使用Parcelable传递数据时数据结构应该尽量简单,避免多重嵌套的发生。




你可能感兴趣的:(数据结构,android,String,Class,menu)