我有一个这样的课程:
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未知类型错误。我是这样做的: 在我的活动的点击监听器中:
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);
}
我不知道为什么我在第二种情况下无法正确传递它。我错过了什么吗?谢谢你的阅读。
答案 0 :(得分: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。