zoukankan      html  css  js  c++  java
  • Android---Parcelable包装类的作用

    android提供了一种新的类型:Parcel。本类被用作封装数据的容器,封装后的数据可以通过Intent或IPC传递。 除了基本类型以外,只有实现了Parcelable接口的类才能被放入Parcel中。Android平台对可通过进程通信(IPC)机制进行传递的数据定义进行约定,这些数据类必须实现Parcelable接口,且必须包含一个类型为Parcelable.Creator且名为CREATOR的公共静态成员。只有实现Parcelable接口的类才能以意向的扩展数据进行传递。

    实现于Parcelable接口的CREATOR成员的createFromParcel方法用于告诉平台如何从包裹里创建该类的实例,而writeToParcel方法则用于告诉平台如何将该类的实例存储到包裹中。通过接口队成员的约定,Android平台可获知数据类的数据读取和写入的接口,从而进行对象的实例化和持久化,该过程如下图:

    示例代码如下:

    public class Person implements Parcelable{
        private String name;
        private String phone;
        //必须包含一个类型为Parcelable.Creator且名为CREATOR的公共静态成员
        private static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
            @Override
            public Person createFromParcel(Parcel source) {//该方法用于告诉平台如何从包裹里创建数据类实例
                return new Person(source);
            }
            @Override
            public Person[] newArray(int size) {
                return new Person[size];
            }
        };
        public Person(String name,String phone){
            this.name = name;
            this.phone = phone;
        }
        public Person(Parcel in){
            this.name = in.readString();
            this.phone = in.readString();
        }
        @Override
        public int describeContents() {
            return 0;
        }
         
        /**
         * 告诉平台如何将数据实例写入Parcel里
         */
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.getName());
            dest.writeString(this.getPhone());
        }
        /**
         * 属性的set和get方法
         * @return
         */
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
         
     
    }
  • 相关阅读:
    Step By Step(C++模板类)
    Step By Step(C++模板重载和特化)
    Step By Step(C++模板推演)
    Step By Step(C++模板Policy)
    Step By Step(C++模板参数)
    Step By Step(C++模板解析)
    Step By Step(C++模板Trait)
    Step By Step(C++模板基本技巧)
    离职引发的诸多感触
    Step By Step(C++模板函数)
  • 原文地址:https://www.cnblogs.com/senior-engineer/p/5002566.html
Copyright © 2011-2022 走看看