抽象类作为包装 [英] Abstract class as parcelable

查看:192
本文介绍了抽象类作为包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我的应用程序中有以下结构:

Basicly I have the following structure in my app:

在没有抽象类 ProjectItem ,但在这种情况下,我不知道如何实现这个。

It would be straightforward to implement such a structure without the abstract class ProjectItem, but in this case I don't know how to implement this.

抽象类 ProjectItem 需要一个 CREATOR ,因为它应该是可包装的。 (如
in.readTypedList(mProjectItems,ProjectItem.CREATOR); 在构造函数Project(Parcel in))

The abstract class ProjectItem needs a CREATOR as it should be parcelable. (like in.readTypedList(mProjectItems, ProjectItem.CREATOR); within the constructor Project(Parcel in))

但实际上,由于逻辑原因, CREATOR 只能在派生类中实现。

But in fact, the CREATOR can only be implemented in its derived classes for logical reasons.

所以,如何实现这个结构,以保持类 Project parcelable ??

So, how to implement this structure in order to keep the class Project parcelable??

编辑

这是 Project 的构造函数之一如下所示:

This is what one of the constructors of Project looks like:

private Project(Parcel in) {
    in.readTypedList(mProjectItems, ProjectItem.CREATOR);
}

但正如我已经说过的, ProjectItem 不应该实现一个 CREATOR

But as I already said, ProjectItem shouldn't have to implement a CREATOR

推荐答案

选择的答案(来自evertvandenbruel的帖子)有一个错误。当只有一个子类被分配时,正确的代码必须考虑到parsling,而不仅仅是超类对象的列表。

The selected answer (from evertvandenbruel's post) has a bug in it. The correct code must account for parceling when just one of the subclasses is being parceled, not just a list of the superclass objects.

所有其他代码应该是一样的,关键是你必须在所有创建者中读取类型变量(见下面的代码)。否则,当尝试打开子类对象时,会出现排序问题

All the other code should be the same, the key is that you MUST read in the type variable in ALL creators (see code below). Otherwise there will be issues with the ordering when trying to unparcel a subclass object

Ex:

package com.example.parcelable_example.model;

import android.os.Parcel;
import android.os.Parcelable;

public class Cat extends Animal{

    public Cat(String name){
        super(name, "Cat");
    }

    public int describeContents() {
        return this.hashCode();
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(getType());
        super.writeToParcel(dest, flags);
    }

    public Cat(Parcel source) {
        super(source);      
    }

    public static final Parcelable.Creator<Cat> CREATOR = new Parcelable.Creator<Cat>() {
        public Cat createFromParcel(Parcel in) {
            /** DO NOT FORGET THIS!!! **/
            type = in.readString();
            return new Cat(in);
        }

        public Cat[] newArray(int size) {
            return new Cat[size];
        }
    };

}

这篇关于抽象类作为包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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