Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android_Parcelable

Android_Parcelable

編輯:關於Android編程

 

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 CREATOR = new Parcelable.Creator() {
		@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 + ];
	}
	
}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved