当前位置:   article > 正文

kotlin使用Parcelize注解简化Parcelable的书写_kotlin parcelable注解

kotlin parcelable注解

kotlin使用Parcelize注解简化Parcelable的书写

Parcelize注解

kotlin在1.1.4版本增加了对parcelable的支持

Android扩展插件现在包含一个实现了Parcelable的自动生成器。在主构造函数中声明序列化的属性并添加一个@Parcelize注解,生成器就会自动创建writeToParcel()/ createFromParcel()方法

需求环境

Kotlin版本为1.1.4或者更高

开始使用

在build.gradle中添加支持

apply plugin: ‘kotlin-android-extensions....
androidExtensions {
    experimental = true
}
  • 1
  • 2
  • 3
  • 4
  • 5

实体类

Student.kt

@Parcelize
data class Student(val id: String, val name: String, val grade: String) : Parcelable
  • 1
  • 2

对比Java实体类

Student.java

public class Student implements Parcelable{
        private String id;
        private String name;
        private String grade;

        // Constructor
        public Student(String id, String name, String grade){
            this.id = id;
            this.name = name;
            this.grade = grade;
       }
       // Getter and setter methods
       .........
       .........

       // Parcelling part
       public Student(Parcel in){
           String[] data = new String[3];

           in.readStringArray(data);
           // the order needs to be the same as in writeToParcel() method
           this.id = data[0];
           this.name = data[1];
           this.grade = data[2];
       }

       @Оverride
       public int describeContents(){
           return 0;
       }

       @Override
       public void writeToParcel(Parcel dest, int flags) {
           dest.writeStringArray(new String[] {this.id,
                                               this.name,
                                               this.grade});
       }
       public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
           public Student createFromParcel(Parcel in) {
               return new Student(in); 
           }

           public Student[] newArray(int size) {
               return new Student[size];
           }
       };
   }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

关于Lint检查报错

现在Android Studio会爆出下面图中的这个错误,这是IntelliJ的Bug,你可以在下面的链接找到相应的答案

https://youtrack.jetbrains.com/issue/KT-19300

这里写图片描述

所以你可以忽略这个警告并编译项目,或者也可以添加@SuppressLint(“ParcelCreator”)注解

英文原文链接

https://android.jlelse.eu/yet-another-awesome-kotlin-feature-parcelize-5439718ba220

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/259865?site
推荐阅读
相关标签
  

闽ICP备14008679号