您当前的位置: 首页 >  ar

蓝不蓝编程

暂无认证

  • 0浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

蓝不蓝编程 发布时间:2019-02-21 18:18:24 ,浏览量:0

内容简介

安卓里在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(intent.getParcelableExtra("extraKey"))
infoTextView.text = user.name
源代码

https://gitee.com/cxyzy1/intentTransDataDemos

安卓开发技术分享: https://blog.csdn.net/yinxing2008/article/details/84555061

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0406s