采用Parceler高效快速在intent间传递对象

内容简介

安卓里在intent间传递数据时,一般采用Parcelable,但是这个东东写起来稍显麻烦,后续在对象里增减字段也要谨慎维护。有牛人写了个简化Parcelable的处理方式,即Parceler,试用了下,使用起来确实较为简单。不过也有一个问题,如果传递的对象是kotlin类,会报错(rg.parceler.ParcelerRuntimeException: Unable to find generated Parcelable class for),只能采用java类;如果要采用kotlin类,可以参考文章:https://www.jianshu.com/p/a32ecbfab6b0

使用方式

  1. build.gradle文件添加依赖
implementation 'org.parceler:parceler-api:1.1.12'
annotationProcessor 'org.parceler:parceler:1.1.12'
  1. 定义数据类User.java:
import org.parceler.Parcel;

@Parcel
public class User {
    String name;
    int age;

    public User() {}

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
  1. 通过intent传递对象:
var intent = Intent(this@MainActivity, SecondActivity::class.java)
val user = User(10, "Andy")
intent.putExtra("extraKey", Parcels.wrap(user))
startActivity(intent)
  1. 通过intent接收对象:
val user = Parcels.unwrap<User>(intent.getParcelableExtra("extraKey"))
infoTextView.text = user.name

源代码

https://gitee.com/cxyzy1/intentTransDataDemos

安卓开发技术分享: https://www.jianshu.com/p/442339952f26

《采用Parceler高效快速在intent间传递对象》

    原文作者:程序园中猿
    原文地址: https://www.jianshu.com/p/074fce8c81f4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞