Activitie之间传对象,通过Parcelable

本文介绍了如何通过自定义 Parcelable 类来实现对象的序列化与反序列化,包括对象的创建、传递和接收过程。重点在于实现 Serializable 接口和 Parcelable 接口的结合,使得对象能够在不同应用间共享和传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对象必须实现Serializable,对象代码如下:

import java.io.Serializable;

import android.graphics.drawable.Drawable;

//传送的对象
public class MyApplicationInfo extends Object implements Serializable{ //Your code }

 

自定义:AppParcelable

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

import com.tcad.marketassistant.vo.MyApplicationInfo;

public class AppParcelable implements Parcelable {

	private MyApplicationInfo info;
	
	public AppParcelable(Parcel source){
		
		info = (MyApplicationInfo)source.readValue(MyApplicationInfo.class.getClassLoader());
			
	}
	
	public AppParcelable(MyApplicationInfo info){
		
		this.info = info;
	}
	
	public int describeContents() {
		
		return 0;
	}

	public void writeToParcel(Parcel dest, int flags) {
		
		dest.writeValue(info);
	}


	public static final Parcelable.Creator<AppParcelable> CREATOR = new Parcelable.Creator<AppParcelable>() {

		public AppParcelable createFromParcel(Parcel source) {
			
			return new AppParcelable(source);
		}

		public AppParcelable[] newArray(int size) {
			
		//	return new AppParcelable[size];
			throw new UnsupportedOperationException(); 
		}
		
	};
	
	public MyApplicationInfo getInfo(){
		
		return info;
	}
}

 调用代码,发送:

AppParcelable parcelable = new AppParcelable(info);
//Info为MyApplicationInfo对象			
			// 发送对象
			intent.putExtra("app_parcelable", parcelable);
			
			startActivity(intent);

 接收:

AppParcelable p = getIntent().getParcelableExtra("app_parcelable");
			
			MyApplicationInfo info = p.getInfo();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值