栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用意图将对象从一个Android活动发送到另一个?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用意图将对象从一个Android活动发送到另一个?

如果您只是传递对象,那么Parcelable就是为此而设计的。与使用Java的本机序列化相比,使用它需要付出更多的努力,但是它的速度更快(我的意思是,WAY更快)。

在文档中,有关如何实现的一个简单示例是:

// simple class that just has one member property as an examplepublic class MyParcelable implements Parcelable {    private int mData;        // 99.9% of the time you can just ignore this    @Override    public int describeContents() {        return 0;    }    // write your object's data to the passed-in Parcel    @Override    public void writeToParcel(Parcel out, int flags) {        out.writeInt(mData);    }    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {        public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in);        }        public MyParcelable[] newArray(int size) { return new MyParcelable[size];        }    };    // example constructor that takes a Parcel and gives you an object populated with it's values    private MyParcelable(Parcel in) {        mData = in.readInt();    }}

请注意,如果要从给定的宗地中检索多个字段,则必须按照将其放入的相同顺序(即,采用FIFO方法)进行操作。

一旦实现Parcelable了对象,只需使用putExtra()将它们放入您的Intent中即可:

Intent i = new Intent();i.putExtra("name_of_extra", myParcelableObject);

然后,您可以使用getParcelableExtra()将它们拉出:

Intent i = getIntent();MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");如果您的对象类实现了Parcelable和Serializable,则请确保将其强制转换为以下之一:i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);i.putExtra("serializable_extra", (Serializable) myParcelableObject);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/367017.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号