之前見到時直接使用,不知其理,在網上查了相關資料,算是有所了解,整理如下:
bundle的用法:
Bundle相當於Map類,就是一個映射,用Bundle綁定數據,便於數據處理
它主要作用於Activity之間的數據傳遞.
兩個activity之間的通訊可以通過bundle類來實現,做法就是:
一、新建一個bundle類
Bundle mBundle = new Bundle();
二、bundle類中加入數據(key -value的形式,另一個activity里面取數據的時候,就要用到key,找出對應的value)
mBundle.putString("Data", "data from TestBundle");
三、新建一個intent對象,並將該bundle加入這個intent對象
Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
intent.putExtras(mBundle);
四、取出數據
Bundle bundle = getIntent().getExtras(); //得到傳過來的bundle
String data = bundle.getString("Data");
重要方法
clear():清除此Bundle映射中的所有保存的數據。
clone():克隆當前Bundle
containsKey(String key):返回指定key的值
getString(String key):返回指定key的字符
hasFileDescriptors():指示是否包含任何捆綁打包文件描述符
isEmpty():如果這個捆綁映射為空,則返回true
putString(String key, String value):插入一個給定key的字符串值
readFromParcel(Parcel parcel):讀取這個parcel的內容
remove(String key):移除指定key的值
writeToParcel(Parcel parcel, int flags):寫入這個parcel的內容
與SharedPreferences的區別
SharedPreferences是簡單的存儲持久化的設置,就像用戶每次打開應用程序時的主頁,它只是一些簡單的鍵值對來操作。它將數據保存在一個xml文件中
Bundle是將數據傳遞到另一個上下文中或保存或回復你自己狀態的數據存儲方式。它的數據不是持久化狀態。
