首页 > 代码库 > Android_Parcelable

Android_Parcelable

本博文为子墨原创,转载请注明出处!
http://blog.csdn.net/zimo2013/article/details/39339033

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Intent intent = getIntent();
		if (intent != null) {
			Parcelable p = intent.getParcelableExtra("info");
			if (p != null) {
				System.out.println(p);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	public void start(View view) {
		Intent intent = new Intent(getApplicationContext(), MainActivity.class);
		intent.putExtra("info", new Bean(100, "baidu"));
		startActivity(intent);
	}

}
import android.os.Parcel;
import android.os.Parcelable;

public class Bean implements Parcelable {
	int age;
	String name;

	public Bean(int age, String name) {
		this.age = age;
		this.name = name;
	}

	@Override
	public int describeContents() {
		//
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		//向dest容器中写入数据,int占4个字节,至于区分String应该有特殊的标志位,相当于反序列化
		dest.writeInt(this.age);
		dest.writeString(this.name);
	}

	public static final Parcelable.Creator<Bean> CREATOR = new Parcelable.Creator<Bean>() {
		@Override
		public Bean createFromParcel(Parcel source) {
			//按照顺序从source中解析出数据,相当于序列化
			int age = source.readInt();
			String name = source.readString();
			return new Bean(age, name);
		}

		@Override
		public Bean[] newArray(int size) {
			return new Bean[size];
		}
	};

	@Override
	public String toString() {
		return "Bean [age=" + age + ", name=" + name + "]";
	}
	
}


Android_Parcelable