Android的Parcelable和序列化 [英] Android Parcelable and Serializable

查看:92
本文介绍了Android的Parcelable和序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道它是推荐使用的,而不是串行化的机器人Parcelable,因为它更快。

So i know it is recommended to use Parcelable instead of Serializable in android, because it is faster.

我的问题是:是无法避免使用序列化权

My question is: is that impossible to avoid using Serializable right?

如果我有我想要序列化的自定义对象,让我们说我有下面的类定义

If I have a custom object i want to serialize, let's say I have the following class definition

public class Person {
   String name;
   int Age;
   ...
   ....
}

进行此parcelable很容易,因为Person类包含的类型parcel.write *()支持,即有parcel.writeString和parcel.writeInt

Making this parcelable is easy, because the Person class contains the types parcel.write*() supports, i.e. there is parcel.writeString and parcel.writeInt

现在,如果Person类如下:

Now, what if the Person class is the following:

public class PersonTwo {
   MyCustomObj customObj;
   String name;
   int Age;
   ...
   ....
}

我怎么猜想包裹MyCustomObj对象? 看来我需要使用序列化了吗?但同样,我认为它是缓慢的使用序列化,似乎我们没有选择,只能使用它在这种情况下。

How am I suppose to parcel the MyCustomObj object?? It seems I need to use serializable again? but again, I thought it is SLOW to use serializable, and seems we have no choice but to use it in this case.

我不明白

有人可以告诉我,我怎么会包裹PersonTwo在这种情况下?

can someone tell me how I would parcel PersonTwo in this case?

推荐答案

由阿贾伊给出的链接是确切的,你在找什么,你如何能做到这一点。 那么,你能做的就是执行 Parcelable CustomObject1 并创建一个 Parcelable 类,然后您可以使用 Parcelable 包裹是 Parcelable 类,将包裹均 CustomObjects

The link given by Ajay is the exact what you are looking for, how you can do it. Well, what you can do is implement Parcelable to your CustomObject1 and create a Parcelable class for it and then you can use that Parcelable class to Parcel it inside another Parcelable class that will Parcel both the CustomObjects.

public class CustomObject1 implements Parcelable {

   // parcelable code CustomObject1
}

public class CustomObject2 implements Parcelable {

    private CustomObject1 obj1;

   // add  CustomObject1 here with getter setter
   // parcelable code for CustomObject2 

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(obj1, flags);
    }  
    private void readFromParcel(Parcel in) {
        obj1 = in.readParcelable(CustomObject1.class.getClassLoader());
    }
  ............
}

这篇关于Android的Parcelable和序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆