使用 Parcelable 通过 intent put 参数传递列表

Use of Parcelable to pass a list through an intent put parameters

我有一张 Class 我制作的卡片列表,我需要通过意图将它传递给另一个 activity。

我正在尝试按照某人的建议实施 Parcelable。

事实是这个列表包含的对象是其他 classes 的模式,扩展了 Card one。

所以例如我有这个 Guard class 它扩展了 Card,但是当我 运行 这个应用程序时我得到这个错误:

Error:(10, 19) error: constructor Card in class Card cannot be applied to given types; required: Parcel found: no arguments reason: actual and formal argument lists differ in length

卡片class如下:

public class Card implements Parcelable{
private String mName;

protected Card(Parcel in) {
    mName = in.readString();
}

public static final Creator<Card> CREATOR = new Creator<Card>() {
    @Override
    public Card createFromParcel(Parcel in) {
        return new Card(in);
    }

    @Override
    public Card[] newArray(int size) {
        return new Card[size];
    }
};



public String getName(){
    return mName;
}
public void setName(String name){
    mName = name;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(mName);
}

}

实现了两种方法,AndroidStudio告诉我添加,我让它自己添加,它们是describeContents()writeToParcel() 但是正如你所看到的,我在所有其他(总共 6 个)class 中得到了另一个错误 extend Card(并且 包含在 List 我需要通过 n intent)

这个是守卫class(其他5个都一样)

public class Guard extends Card {

public Guard(){
    this.setName("Guard");
}

}

您认为问题是什么?我应该如何解决这个以及为什么?

我就是这样创建 intent:

Intent intent = new Intent(this, RandomAssignment.class);
intent.putParcelableArrayListExtra("CHARACTERS", (ArrayList<? extends Parcelable>) characters);
startActivity(intent);

以及如何检索它:

characters = this.getIntent().getParcelableArrayListExtra("CHARACTERS");

以及 Doc

ArrayList public class ArrayList extends AbstractList implements Cloneable, Serializable, RandomAccess

其清晰的ArrayList不可分割

创建 CustomClass 扩展 ArrayList 实现 Parcelable。 然后在 Intent 中使用它作为 putParcelableArrayListExtra

您还有一个选择 Serializable,只需将标记添加到 ArrayListItems

如果你想让你的 class Parcelable 包含另一个 class 的对象,你需要先使那个 class Parcelable 。

列出您的包裹清单class

Intent i = new Intent(this,SecondActivity.class);
i.putParcelableArrayList("YOUR_KEY", new ArrayList<ParcelableClass>(Arraylistobject));

检索列表

ArrayList<ParcelableClass> testing = this.getIntent().getParcelableArrayListExtra("Your_KEY");

你绝对应该先从官方文档和这里阅读 Parcelable https://guides.codepath.com/android/using-parcelable