删除持有Intent的ClipData会产生BadParcelableException

时间:2018-05-10 20:00:31

标签: android

我正在尝试使用持有Intent的ClipData拖放对象。以下代码在解组时给出BadParcelableException:ClassNotFoundException:nl.braaks55.parcelable.Card。有人知道如何解决这个问题?应该指定ClassLoader吗?

以下代码:

dragButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            Intent intent = new Intent();
            intent.putExtra("card", new Card("Hearts", "Queen"));

            ClipData clipData = ClipData.newIntent("card", intent);
            View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder();

            view.startDrag(clipData, shadowBuilder, null, 0);

            return true;
        }
    });

    dropButton.setOnDragListener(new View.OnDragListener() {
        @Override
        public boolean onDrag(View view, DragEvent dragEvent) {
            switch (dragEvent.getAction()) {
                (...)
                case DragEvent.ACTION_DROP:
                    ClipData clipData = dragEvent.getClipData();
                    ClipData.Item item = clipData.getItemAt(0);
                    Intent intent = item.getIntent();
                    // The following line gives a BadParcelableException
                    Card card = intent.getParcelableExtra("card");
                    break;
            }

            return true;
        }
    });

public class Card implements Parcelable {
    private String color;
    private String rank;

    Card(String color, String rank) {
        this.color = color;
        this.rank = rank;
    }

    protected Card(Parcel in) {
        color = in.readString();
        rank = 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];
        }
    };

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

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

1 个答案:

答案 0 :(得分:1)

是的,你应该指定类加载器。只需添加一行:

Intent intent = item.getIntent();
intent.setExtrasClassLoader(Card.class.getClassLoader());
Card card = intent.getParcelableExtra("card");

现在它有效。