简体   繁体   English

是否可以创建一个具有空构造函数的 Parcelable Class?

[英]Is it possible to create a Parcelable Class that has an empty constructor?

I'm trying to use firestore recycler adapter with a parcelable class, but it needs to have an empty constructor.我正在尝试使用带有可打包 class 的 Firestore 回收器适配器,但它需要有一个空的构造函数。

My solution now is to create a regular class with an empty constructor and right after fetching the data, I'll map the objects into a parcelable copy.我现在的解决方案是创建一个带有空构造函数的常规 class 并在获取数据后立即将 map 对象放入可打包的副本中。

But is it possible to create a Parcelable Class with an empty constructor?但是是否可以使用空构造函数创建 Parcelable Class ? In Android Studio when I do right click -> Generate -> I see no secondary constructor option so I guess it's not possible, right?在 Android Studio 中,当我右键单击 -> 生成 -> 我没有看到辅助构造函数选项,所以我想这是不可能的,对吧?

Yes, it is possible .是的,这是可能的 The Parcelable object will be serialized and deserialized without any problem. Parcelable object 将被序列化和反序列化没有任何问题。

In Android Studio when I do right click -> Generate -> I see no secondary constructor option so I guess it's not possible, right?在 Android Studio 中,当我右键单击 -> 生成 -> 我没有看到辅助构造函数选项,所以我想这是不可能的,对吧?

No , the fact that it doesn't appear as suggestion in Android Studio code completion feature doesn't mean it is not possible.,它在 Android Studio 代码完成功能中没有作为建议出现这一事实并不意味着它不可能。

Taking as a reference the Parcelable implementation from Android documentation .Android 文档中的 Parcelable 实现作为参考。 You should then need to add an empty constructor.然后,您应该需要添加一个空的构造函数。 Just write the code, don't use code generator.只写代码,不要使用代码生成器。

public MyParcelable(){
}

The class then should look like this: class 应如下所示:

public class MyParcelable implements Parcelable {
    private int mData;

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    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];
        }
    };

    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }

    public MyParcelable(){
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM