xamarin android bundle放入parcelable数组

时间:2017-08-21 13:33:23

标签: android xamarin.android bundle parcelable

我需要在bundle中保存对象数组,这就是我所做的:

创建实现IParcable接口的类:

 public class SimpleSelectorItem : Java.Lang.Object, Android.OS.IParcelable
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Selected { get; set; }

        IntPtr IJavaObject.Handle { get { return IntPtr.Zero; } }

        public int DescribeContents()
        {
            return 0;
        }

        public SimpleSelectorItem()
        {

        }

        public SimpleSelectorItem(int id, string name)
        {
            Id = id;
            Name = name;
        }

        public SimpleSelectorItem(Parcel parcel)
        {
            Id = parcel.ReadInt();
            Name = parcel.ReadString();
        }

        public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags)
        {
            dest.WriteInt(Id);
            dest.WriteString(Name);
        }

        static readonly GenericParcelableCreator<SimpleSelectorItem> _creator
       = new GenericParcelableCreator<SimpleSelectorItem>((parcel) => new SimpleSelectorItem(parcel));

        [ExportField("CREATOR")]
        public static GenericParcelableCreator<SimpleSelectorItem> GetCreator()
        {
            return _creator;
        }
    }

当我创建我的片段实例时,尝试在bundle中设置SimpleSelectorItem数组:

     var items = _viewModel.GetEmployees().Select(l => new SimpleSelectorItem(l.Id, l.LegalName)).ToArray();
      ....
     args.PutParcelableArray(ITEMS, items);

但是当我回到这个数组时,它是空数组...

 var items = Arguments.GetParcelableArray(ITEMS); 

这是演示应用程序,它在我尝试投射项目时抛出异常: enter image description here

1 个答案:

答案 0 :(得分:1)

  

但是当我回到这个数组时,它就是空数组......

我已经测试过该项目。数据正确传递,但是投射失败了。

要解决此问题,您需要以不同方式强制转换数组:

SetData方法:

private void SetData(View rootView)
    {
       ...
       //use the following line to retrieve and cast the items to SimpleSelectorItem[]
        var items = Arguments.GetParcelableArray(ITEMS).Cast<SimpleSelectorItem>().ToList();

        _lvSelector = (ListView)rootView.FindViewById(Resource.Id.lvSelector);
        //pass the items to your adapter.
        SimpleSelectorListAdapter adapter = new SimpleSelectorListAdapter(Activity, items);
        _lvSelector.Adapter = adapter;
    }