Activitie之间传对象,通过Parcelable

本文介绍了一种在Android应用中通过Parcelable接口实现复杂对象传递的方法,包括自定义对象MyApplicationInfo实现Serializable接口,以及AppParcelable类如何包装该对象并实现Parcelable接口以支持Intent传递。

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

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

Java代码
  1. import java.io.Serializable;  
  2.   
  3. import android.graphics.drawable.Drawable;  
  4.   
  5. <span style="white-space: normal;"><pre name="code" class="java">//传送的对象</pre>  
  6. </span>  
  7. public class MyApplicationInfo extends Object implements Serializable{  
  8.       
  9.       
  10.     //Your code  
  11.       
  12. }  

 

自定义:AppParcelable

Java代码 
  1. import android.os.Parcel;  
  2. import android.os.Parcelable;  
  3.   
  4. import com.tcad.marketassistant.vo.MyApplicationInfo;  
  5.   
  6. public class AppParcelable implements Parcelable {  
  7.   
  8.     private MyApplicationInfo info;  
  9.       
  10.     public AppParcelable(Parcel source){  
  11.           
  12.         info = (MyApplicationInfo)source.readValue(MyApplicationInfo.class.getClassLoader());  
  13.               
  14.     }  
  15.       
  16.     public AppParcelable(MyApplicationInfo info){  
  17.           
  18.         this.info = info;  
  19.     }  
  20.       
  21.     public int describeContents() {  
  22.           
  23.         return 0;  
  24.     }  
  25.   
  26.     public void writeToParcel(Parcel dest, int flags) {  
  27.           
  28.         dest.writeValue(info);  
  29.     }  
  30.   
  31.   
  32.     public static final Parcelable.Creator<AppParcelable> CREATOR = new Parcelable.Creator<AppParcelable>() {  
  33.   
  34.         public AppParcelable createFromParcel(Parcel source) {  
  35.               
  36.             return new AppParcelable(source);  
  37.         }  
  38.   
  39.         public AppParcelable[] newArray(int size) {  
  40.               
  41.         //  return new AppParcelable[size];  
  42.             throw new UnsupportedOperationException();   
  43.         }  
  44.           
  45.     };  
  46.       
  47.     public MyApplicationInfo getInfo(){  
  48.           
  49.         return info;  
  50.     }  
  51. }  

 调用代码,发送:

Java代码 
  1. AppParcelable parcelable = new AppParcelable(info);  
  2. //Info为MyApplicationInfo对象            
  3.             // 发送对象  
  4.             intent.putExtra("app_parcelable", parcelable);  
  5.               
  6.             startActivity(intent);  

 接收:

Java代码 
  1. AppParcelable p = getIntent().getParcelableExtra("app_parcelable");  
  2.               
  3.             MyApplicationInfo info = p.getInfo();  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值