能解決這個問題真的太讓人興奮,這里要普及一個知識點,那就是所謂的序列化。
序列化:將對象狀態轉換為可保持或傳輸的格式的過程。與序列化相對的是反序列化,它將流轉換為對象。這兩個過程結合起來,可以輕松地存儲和傳輸數據。
大家讀不讀得懂先暫且不說,因為概念什么的東西我也最煩了,大家只要知道用序列化能實現我們想做的事情就OK了(就是標題所說的功能)。
在大多數實戰項目中進行兩個頁面之間的切換時,不會只傳一個int或者string那么輕松,就算是傳稍微加點料的大眾類型(比如int數組或List<string>之類的)其實也沒什么大不了的,因為在Intent類中有多個putExtra的重載方法,足以滿足我們的需求。
但人們總是“貪婪”的,哈哈,有的時候這些簡單的類型無法滿足我們的需求,我們通過會要求傳遞一個自定義的類或者該類的集合,我們不知道這么說大家頭腦中有沒有概念。舉個例子:我們要向另一個activity傳遞一個人(Person)的對象,Android中沒有Person這個類,是我們自定義的。所以要想利用Intent去傳遞Person或者List<Person>這樣的對象,我們就要使用到序列化了。這不是一個好消息嗎?至少我們有解決的辦法了。
在給大家上代碼示例之前,還要再多說點,在Android中使用序列化有兩種方法:(1)實現Serializable接口(2)實現Parcelable接口
其中Parcelable是Android特有的功能,效率要比實現Serializable接口高。實現Serializable接口非常簡單,聲明一下就可以了。而實現Parcelable雖然稍微復雜一些,但效率高,既然是Android特有用來做序列化使用的,那我們就推薦用這種方法。
下面請看代碼示例:
首先需要寫一個實現Parcelable接口的類,代碼中的1,2,3條是實現Parcelable接口序列化對象必須要有的。
//1、實現Parcelable接口 public class Person implements Parcelable{ private String name private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { returnthis.name; } public void setName(String name) { this.name = name; } public int getAge() { returnthis.age; } public void setAge(int age) { this.age = age; } @Override public int describeContents() { return 0; } //2、實現Parcelable接口的public void writeToParcel(Parcel dest, int flags)方法 //通常進行重寫 @Override public void writeToParcel(Parcel dest, int flags) { //把數據寫入Parcel dest.writeString(name); dest.writeInt(age); } //3、自定義類型中必須含有一個名稱為CREATOR的靜態成員,該成員對象要求實現Parcelable.Creator接口及其方法 public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { @Override public Person createFromParcel(Parcel source) { //從Parcel中讀取數據 //此處read順序依據write順序 return new Person(source.readString(), source.readInt()); } @Override public Person[] newArray(int size) { return new Person[size]; } }; }
這樣一個實現Parcelable接口序列化類就創建好了,那么我們如何用其來進行傳遞呢?在原activity中我們需要這樣傳遞數據
ArrayList<Person> lPersonSet = new ArrayList<Person>(); Person p1 = new Person(“張三”,20); lPersonSet.add(p1); Person p2 = new Person(“李四”,22); lPersonSet.add(p2); Person p3 = new Person(“王五”,21); lPersonSet.add(p3); //進行頁面跳轉 Intent intent = new Intent(); intent.putParcelableArrayListExtra("com.example.utilities.personset", lPersonSet); intent.setClass(MyActivity.this, OtherActivity.class); MyActivity.this.startActivity(intent);
而在OtherActivity中呢?我們需要這樣接收數據
ArrayList<Person> lPersonSet = new ArrayList<Person>(); Intent intent = getIntent(); lPersonSet = intent.getParcelableArrayListExtra("com.example.utilities.personset");
這樣就搞定一切了,其他的形式大家可以自由發揮了,重點還是在如何實現Parcelable接口序列化類上。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。