0

我有这样的课:

public class Images implements Parcelable {
    public String[] imageUrls = new String[]{"url1", "url2"};
    public String[] imageThumbUrls = new String[]{"url3", "url4"};
    public Images(){}
    public Images(Parcel in){
        this.imageUrls = (String[]) in.readArray(String.class.getClassLoader());
        this.imageThumbUrls = (String[]) in.readArray(String.class.getClassLoader());
    }
    public int describeContents(){return 0;}
    public void writeToParcel(Parcel dest, int flags){
        dest.writeStringArray(imageUrls);
        dest.writeStringArray(imageThumbUrls);
    }
    public static final Parcelable.Creator<Images> CREATOR = new Parcelable.Creator<Images>(){
        public Images createFromParcel(Parcel source){return new Images(source);}
        public Images[] newArray(int size){return new Images[size];}
    };
}

当我将它从 FragmentActivity 传递给 Fragment 时,它很好。我是这样做的: 在 FragmentActivity 中:

MyFragment.newInstance(new Images());

在片段中:

public static MyFragment newInstance(Images imgs){
    MyFragment mf = new MyFragment();
    Bundle args = new Bundle();
    args.putParcelable(TAG, imgs);
    mf.setArguments(args);
    return mf;
}
public void onCreate(Bundle s){Images imgs = getArguments().getParcelable(TAG);}

但是,当我尝试将它从 Activity 传递给 FragmentActivity 时,它会显示 Unmarshalling unknown type error。我是这样做的:在我的活动的点击监听器中:

public void onClick(View v){
    Intent i = new intent(v.getContext(), MyFragmentActivity.class);
    i.putExtra(TAG, new Images());
    v.getContext().startActivity(i);
}

在我的 FragmentActivity 中:

public void onCreate(Bundle s){
    Images imgs = getIntent().getParcelableExtra(TAG);
}

我不知道为什么我在第二种情况下无法正确通过,而我在第一种情况下成功了。有什么我错过的吗?感谢您的阅读。

4

1 回答 1

0

好的,我成功了。我更改了图像中的构造函数:来自:

public Images(Parcel in) {
    this.imageUrls = (String[]) in.readArray(String.class.getClassLoader());
    this.imageThumbUrls = (String[]) in.readArray(String.class.getClassLoader());
}

至:

public Images(Parcel in) {
    in.readStringArray(this.imageUrls);
    in.readStringArray(this.imageThumbUrls);
}

但我仍然想知道为什么它在原来的情况下成功了——从 MyFragmentActivity 传递到 MyFragment。

于 2013-08-02T17:32:14.573 回答