由于实际工作需要,可能会遇到Intent传递对象的情况,这种情况稍稍麻烦一点,在这里有三种方法可以解决这个问题:
(1) ISerializable接口
(2) IParcelable接口
(3)利用Json对对象进行序列化->反序列,得到原对象(个人推荐第三种,原因:使用简单,一两句话的事情)
这里我将采用第二种方法和第三种方法实验,各位看官可以自行对比。
方法一:利用IParcelable接口
1 新建一个类Student,继承IParcelable接口
- public class Student : Java.Lang.Object, IParcelable
- {
- public string Name { get; set; }
- public string Sex { get; set; }
- public Student()
- {
- }
- private Student(Parcel parcel)
- {
- Sex = parcel.ReadString();
- Name = parcel.ReadString();
- }
- public int DescribeContents()
- {
- return 0;
- }
- public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
- {
- dest.WriteString(Sex);
- dest.WriteString(Name);
- }
- #region IParcelable implementation
- // The creator creates an instance of the specified object
- private static readonly GenericParcelableCreator<Student> _creator
- = new GenericParcelableCreator<Student>((parcel) => new Student(parcel));
- [ExportField("CREATOR")]
- public static GenericParcelableCreator<Student> GetCreator()
- {
- return _creator;
- }
- #endregion
- }
- /// <summary>
- /// Generic Parcelable creator that can be used to create objects from parcels
- /// </summary>
- public sealed class GenericParcelableCreator<T> : Java.Lang.Object, IParcelableCreator
- where T : Java.Lang.Object, new()
- {
- private readonly Func<Parcel, T> _createFunc;
- /// <summary>
- /// Initializes a new instance of the <see cref="GenericParcelableCreator{T}"/> class.
- /// </summary>
- /// <param name='createFromParcelFunc'>
- /// Func that creates an instance of T, populated with the values from the parcel parameter
- /// </param>
- public GenericParcelableCreator(Func<Parcel, T> createFromParcelFunc)
- {
- _createFunc = createFromParcelFunc;
- }
- #region IParcelableCreator Implementation
- public Java.Lang.Object CreateFromParcel(Parcel source)
- {
- return _createFunc(source);
- }
- public Java.Lang.Object[] NewArray(int size)
- {
- return new T[size];
- }
- #endregion
- }
2 新建Activity1为测试,在MainActivity中发送对象,代码如下:
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- SetContentView(Resource.Layout.Main);
- Button button = FindViewById<Button>(Resource.Id.MyButton);
- button.Click += delegate
- {
- Student stu=new Student();
- stu.Name = "Intent对象";
- stu.Sex = "第五种生物";
- button.Text = string.Format("{0} clicks!", count++);
- Intent intent=new Intent(this,typeof(Activity1));
- intent.PutExtra("mode", stu);
- StartActivity(intent);
- };
- }
在Activity中接收对象:
- public class Activity1 : Activity
- {
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- var my_class = Intent.GetParcelableExtra("mode") as Student;
- }
- }
Debug结果:
方法二:利用Json对对象进行序列化(需自己添加Json库)
参考文章地址:
最后附上Demo地址:http://download.csdn.net/detail/sinat_26562875/9477273
请大家多多指正~~~
发表评论