Android---Parcelable封裝類的作用

來源:互聯網
上載者:User

標籤:

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;    }      }

Android---Parcelable封裝類的作用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.