安卓通过Intent传递自定义类

1.Serializable(不推荐)
实现要点:类继承Serializable接口
举例:MainActivity通过Intent跳转到SubActivity的时候传递Test类实例test。
MainActivity.java
    Intent intent = new Intent(MainActivity.this, SubActivity.class);
    Test test = new Test();
    test.name = "hello";
    intent.putExtra("test", test);
    startActivity(intent);
SubActivity.java
    Intent intent = getIntent();
    Test test = (Test)intent.getSerializableExtra("test");
Test.java
    public class Test implements Serializable
    {
        public String name;
    }
2.Parcelable(推荐)
实现要点: 类继承Parcelable接口,且需要实现三个东西
1)writeToParcel 方法。
2)describeContents方法。
3)静态的Parcelable.Creator接口,有两个方法:
    createFromParcel(Parcel in) 
    newArray(int size) 
举例:MainActivity通过Intent跳转到SubActivity的时候传递Test类实例test。
MainActivity.java(同上)
    Intent intent = new Intent(MainActivity.this, SubActivity.class);
    Test test = new Test();
    test.name = "hello";
    intent.putExtra("test", test);
    startActivity(intent);
SubActivity.java
    Intent intent = getIntent();
    Test test = intent.getParcelableExtra("test");
Test.java
    public class Test implements Parcelable
    {
        public String name;

        @Override
        public int describeContents()
        {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags)
        {
            dest.writeString(name);
        }

        public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
        {
            public Test createFromParcel(Parcel in)
            {
                Test test = new Test();
                test.name = in.readString();
                return test;
            }
            public Test[] newArray(int size)
            {
                return new Test[size];
            }
        };
}
3.其他有用信息
Parcelable的性能比Serializable好,在内存开销方面较小,所以在内存间数据传输时推荐使用Parcelable,如activity间传输数据,而Serializable可将数据持久化方便保存,所以在需要保存或网络传输数据时选择Serializable。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值