将活动中的Arraylist传递给Fragment

时间:2014-01-16 12:07:49

标签: android parcelable

我有MyClass实现Parcelable。并有2个片段。在MainActivity(onCreate)中,我有代码:

ArrayList<MyClass> data = new ArrayList<MyClass>();
............
Bundle extras1 = new Bundle();
extras1.putParcelableArrayList("arraylist", data);
Tab1Fragment fg = new Tab1Fragment();
fg.setArguments(extras1);

在Fragment(onCreateView)中:

Bundle extras = getArguments(); 
ListView list = (ListView) content.findViewById(R.id.lvMain);
if (extras != null) {
    data = extras.getParcelableArrayList("arraylist");
    list.setAdapter(new MyAdapter(getActivity(), data));
}

但是额外的东西总是空的。为什么?:)

1 个答案:

答案 0 :(得分:3)

您提供的代码似乎没问题。我怀疑问题来自你如何实现MyClass。 Parcelable的典型实现是这样的(取自谷歌)

public class MyParcelable implements Parcelable {
 private int mData;

 public int describeContents() {
     return 0;
 }

 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
 }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

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

 private MyParcelable(Parcel in) {
     mData = in.readInt();
 }