您当前的位置: 首页 >  ar

蓝不蓝编程

暂无认证

  • 3浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

安卓通过Parcelable传值失败解决方案及原理分析

蓝不蓝编程 发布时间:2018-09-06 18:58:56 ,浏览量:3

问题描述:

   在项目中,需要从一个Activity传值到另一个Activity,因为涉及参数较多,所以定义一个Parcelable对象来传值。但是结果接收的地方没有获取到。

   代码如下(代码做了简化):   

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(this.title);
}

protected TransInfo(Parcel in) {
    this.title = in.readString();
}

问题原因:

   因为写的时候,用的时writeValue,而读取的时候用的是readString,不配对。应该写的时候用writeString方法。

原因分析:

   深入Parcel.java源代码查看writeValue方法:其实writeValue方法也调用了writeString,但是在之前还调用了writeInt,所以不能直接readString,除非先把这个写如的Int给读取出来。

验证: 

   基于上面的分析,我修改了代码,增加了“in.readInt();”。

   验证OK。

protected TransInfo(Parcel in) {
	in.readInt();
	this.title = in.readString();
}

正确的做法:

方式一(推荐):

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.title);
}

protected TransInfo(Parcel in) {
	this.title = in.readString();
}

方式二:

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(this.title);
}

protected TransInfo(Parcel in) {
	this.title = (String)in.readValue(String.class.getClassLoader());
}

安卓开发技术分享:https://blog.csdn.net/yinxing2008/article/details/84555061

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0385s