在應用中,可能會在當跳轉到另外一個Activity的時候需要傳遞數據過去,這時就可能用Bundle對象;
在MainActivity中,有一個導航至BActivity的Intent,
Intent
Intent intent = new Intent(Context context, Class<?> class);
//new一個Bundle對象,并將要傳遞的數據導入,Bunde相當于Map<Key,Value>結構
Bundle bundle = new Bundle();
bundle.putString("name","Livingstone");
bundle.putXXX(XXXKey, XXXValue);
//將Bundle對象添加給Intent
intent.putExtras(bundle);
//調用intent對應的Activity
startActivity(intent);
}
Bundle bundle = this.getIntent().getExtras();// 獲取傳遞過來的封裝了數據的Bundle
String name = bundle.getString("name");// 獲取name_Key對應的Value
// 獲取值時,添加進去的是什么類型的獲取什么類型的值
--> bundle.getXXX(XXXKey);
return XXXValue
上面講述的都是一般的基本數據類型,當需要傳遞對象的時候,可以使該對象實現Parcelable或者是Serializable接口;
通過Bundle.putParcelable(Key,Obj)及Bundle.putSerializable(Key,Obj)方法將對象添加到Bundle中,再將此Bundle對象添加到Intent中!
在跳轉的目標頁面通過Intent.getParcelableExtra(Key)獲取實現了Parcelable的對象;
在跳轉的目標頁面通過Intent.getSerializableExtra(Key)獲取實現了Serializable的對象;
今天在研究的時候發現,Intent.putExtra(Key,Value);其實也可以傳遞數據,包括上面所講的對象!
實現Serializable接口很簡單,不再描述;
下面描述實現Parcelable接口:
public static final Parcelable.Creator CREATOR = new Creator() {// 此處必須定義一個CREATOR成員變量,要不然會報錯!
@Override
public Book createFromParcel(Parcel source) {// 從Parcel中獲取數據,在獲取數據的時候需要通過此方法獲取對象實例
Book book = new Book();
book.setAuthor(source.readString());// 從Parcel讀取數據,讀取數據與寫入數據的順序一致!
book.setBookName(source.readString());
return book;
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override// 寫入Parcel
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);// 將數據寫入Parcel,寫入數據與讀取數據的順序一樣!
dest.writeString(bookName);
}
}
一個final類,用于寫或讀各種數據,所有的方法不過就是writeValue(Object)和read(ClassLoader)!(個人翻譯理解)
新聞熱點
疑難解答
圖片精選