Parcel和Parcelable


參考:http://blog.csdn.net/dairyman000/article/details/7247619

arcel 在英文中有兩個意思,其一是名詞,為包裹,小包的意思; 其二為動詞,意為打包,扎包。郵寄快遞中的包裹也用的是這個詞。Android采用這個詞來表示封裝消息數據。這個是通過IBinder通信的消息的載 體。需要明確的是Parcel用來存放數據的是內存(RAM),而不是永久性介質(Nand等)。

Parcelable,定義了將數據寫入Parcel,和從Parcel中讀出的接口。一個實體(用類來表示),如果需要封裝到消息中去,就必須實現這一接口,實現了這一接口,該實體就成為“可打包的”了。

接口的定義如下:

public interface Parcelable {
    //內容描述接口,基本不用管
    public int describeContents();
    //寫入接口函數,打包
    public void writeToParcel(Parcel dest, int flags);
     //讀取接口,目的是要從Parcel中構造一個實現了Parcelable的類的實例處理。因為實現類在這里還是不可知的,所以需要用到模板的方式,繼承類名通過模板參數傳入。
    //為了能夠實現模板參數的傳入,這里定義Creator嵌入接口,內含兩個接口函數分別返回單個和多個繼承類實例。
    public interface Creator<T> {
           public T createFromParcel(Parcel source);
           public T[] newArray(int size);
    }
}

下面定義了一個簡單類People, 他需要把自身的數據,打入包中。 同時在消息的接收方需要通過People實現的Parcelable接口,將People重新構造出來。

People.java
public
class People implements Parcelable { private String name = null; private int age = 0; private int sex = 0;// 0代表男、1代表女 public People() { super(); } public People(String name, int age, int sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); dest.writeInt(sex); } public static final Parcelable.Creator<People> CREATOR = new Creator<People>() { @Override public People[] newArray(int size) { return new People[size]; } @Override public People createFromParcel(Parcel source) { return new People(source.readString(), source.readInt(), source.readInt()); } }; }

傳遞People

//發送 MainActivity.java
People people = new People(); people.setName("張三"); people.setSex(Integer.parseInt(0)); people.setAge(Integer.parseInt(25)); Intent intent = new Intent(MainActivity.this, ShowActivity.class); Bundle b = new Bundle(); b.putParcelable("people", people); intent.putExtras(b); MainActivity.this.startActivity(intent);

//接受 ShowActivity.java
if(getIntent().getExtras().containsKey("people")){
  People people = getIntent().getExtras().getParcelable("people");
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM