Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android頁面間傳遞對象

android頁面間傳遞對象

編輯:關於Android編程

android傳遞對象有兩種方式:

一種是Serializable和Parcelable

對於第一種方式:

import java.io.Serializable;


public class ShopData implements Serializable {
public String shopId;
public String name;
public String url;
public String info;


public String getShopId() {
return shopId;
}


public void setShopId(String shopId) {
this.shopId = shopId;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getUrl() {
return url;
}


public void setUrl(String url) {
this.url = url;
}


public String getInfo() {
return info;
}


public void setInfo(String info) {
this.info = info;
}


}

傳遞值的時候這樣來傳遞:

				Intent intent = new Intent();
				ShopData shopData = (ShopData)mAdapter.getItem(position);
//				intent.putExtra("detail", shopData);
				Bundle bundle = new Bundle();
				bundle.putSerializable("shop", shopData);
				intent.putExtra("detail", shopData);
				intent.setClass(MainActivity.this, DetailShopActivity.class);
				MainActivity.this.startActivity(intent);
取值的時候:

		Intent intent = getIntent();
//		ShopData data = intent.getParcelableExtra("detail");
		ShopData data = (ShopData)intent.getSerializableExtra("detail");

對於第二種方式:

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

public class ShopData implements Parcelable{

	public String shopId;
	public String name;
	public String url;
	public String info;

	public ShopData(Parcel in) {
		readFromParcel(in);
	}
	
	public ShopData() {
	}
	

	public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
		
		public ShopData createFromParcel( Parcel in ){
			return new ShopData(in);
		}
		
		public ShopData[] newArray( int size){
			return new ShopData[size];
		}
	};
	
	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(shopId);
		dest.writeString(name);
		dest.writeString(url);
		dest.writeString(info);
		
	}
	public void readFromParcel( Parcel in ){
		shopId = in.readString();
		name = in.readString();
		url = in.readString();
		info = in.readString();
	}
	
}

傳遞的時候這樣寫:

				Intent intent = new Intent();
				ShopData shopData = (ShopData)mAdapter.getItem(position);
				intent.putExtra("detail", shopData);
				intent.putExtra("detail", shopData);
				intent.setClass(MainActivity.this, DetailShopActivity.class);
				MainActivity.this.startActivity(intent);


取值的時候:

		Intent intent = getIntent();
		ShopData data = intent.getParcelableExtra("detail");



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