Android 不同Activity間數(shù)據(jù)的傳遞 Bundle對象的應用
在應用中,可能會在當跳轉到另外一個Activity的時候需要傳遞數(shù)據(jù)過去,這時就可能用Bundle對象;
在MainActivity中,有一個導航至BActivity的Intent,
Intent
{
Intent intent = new Intent(Context context, Class<?> class);
//new一個Bundle對象,并將要傳遞的數(shù)據(jù)導入,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);
}
在BActivity中,通過以下代碼獲取MainActivity所傳過來的數(shù)據(jù)
Bundle bundle = this.getIntent().getExtras();// 獲取傳遞過來的封裝了數(shù)據(jù)的Bundle
String name = bundle.getString("name");// 獲取name_Key對應的Value
// 獲取值時,添加進去的是什么類型的獲取什么類型的值
--> bundle.getXXX(XXXKey);
return XXXValue
上面講述的都是一般的基本數(shù)據(jù)類型,當需要傳遞對象的時候,可以使該對象實現(xiàn)Parcelable或者是Serializable接口;
通過Bundle.putParcelable(Key,Obj)及Bundle.putSerializable(Key,Obj)方法將對象添加到Bundle中,再將此Bundle對象添加到Intent中!
在跳轉的目標頁面通過Intent.getParcelableExtra(Key)獲取實現(xiàn)了Parcelable的對象;
在跳轉的目標頁面通過Intent.getSerializableExtra(Key)獲取實現(xiàn)了Serializable的對象;
今天在研究的時候發(fā)現(xiàn),Intent.putExtra(Key,Value);其實也可以傳遞數(shù)據(jù),包括上面所講的對象!
實現(xiàn)Serializable接口很簡單,不再描述;
下面描述實現(xiàn)Parcelable接口:
public class Book implements Parcelable {
private String bookName;
private String author;
public static final Parcelable.Creator CREATOR = new Creator() {// 此處必須定義一個CREATOR成員變量,要不然會報錯!
@Override
public Book createFromParcel(Parcel source) {// 從Parcel中獲取數(shù)據(jù),在獲取數(shù)據(jù)的時候需要通過此方法獲取對象實例
Book book = new Book();
book.setAuthor(source.readString());// 從Parcel讀取數(shù)據(jù),讀取數(shù)據(jù)與寫入數(shù)據(jù)的順序一致!
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);// 將數(shù)據(jù)寫入Parcel,寫入數(shù)據(jù)與讀取數(shù)據(jù)的順序一樣!
dest.writeString(bookName);
}
}
關于Parcel,大概查閱了一下描述:
一個final類,用于寫或讀各種數(shù)據(jù),所有的方法不過就是writeValue(Object)和read(ClassLoader)!(個人翻譯理解)
相關文章
Android實現(xiàn)Activity、Service與Broadcaster三大組件之間互相調用的方法詳解
這篇文章主要介紹了Android實現(xiàn)Activity、Service與Broadcaster三大組件之間互相調用的方法,結合實例形式詳細分析了Activity、Service與Broadcaster三大組件相互調用的原理,實現(xiàn)方法與相關注意事項,需要的朋友可以參考下2016-03-03Android開發(fā)Jetpack組件ViewModel使用講解
這篇文章主要介紹了Android?Jetpack架構組件?ViewModel詳解,ViewModel類讓數(shù)據(jù)可在發(fā)生屏幕旋轉等配置更改后繼續(xù)存在,ViewModel類旨在以注重生命周期的方式存儲和管理界面相關的數(shù)據(jù),感興趣可以來學習一下2022-08-08Android實現(xiàn)移動小球和CircularReveal頁面切換動畫實例代碼
這篇文章主要給大家介紹了關于利用Android如何實現(xiàn)移動的小球和CircularReveal頁面切換動畫的相關資料,文中通過示例代碼介紹的非常詳細,對各位Android開發(fā)者們具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-09-09Android Webview的postUrl與loadUrl加載頁面實例
這篇文章主要介紹了Android Webview的postUrl與loadUrl加載頁面實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03