Bundle類用作攜帶數據,它類似于Map,用于存放key-value形式的值,相對于Map,它提供了各種常用類型的putXxx()/getXxx()方法,Bundle的內部實際上是使用了HashMap類型的變量來存放PutXxx()方法存入的值。
?SDK里是這樣描述:A mapping from String values to various Parcelable types。它幫助我將數據打包傳入intent里面,為使用這些數據提供了便利。
java代碼:
-
- protected void onListItemClick (ListView l, View v, int position, long id)
- {
- super.onListItemClick(l, v, position, id);
-
- //獲得選中項的HashMap對象?
- HashMap map=(HashMap)lv.getItemAtPosition(position);
- String Type=map.get("Type");?
- Intent i=new Intent(this,title.class);
- Bundle mBundle=new Bundle();
- mBundle.putString("type", Type);
- i.putExtras(mBundle);
- startActivity(i);
- }
-
?
???????1、實例化Bundle 一個對象,用putString(標記,數據)來將數據導入到Bundle對象中;
2、然后將Bundle對象導入到Intent對象中;
3、Intent啟動另一個activity。
從intent中讀出需要的數據:
java代碼:
- bundle = getIntent().getExtras();?
- if(bundle!=null)
- Type=bundle.getString("type");
- if(Type!=null)?
- //從數據庫依據所選類型讀出 文章的Title,保存在cur中?
- cur=myDBadapter.getTitle(new String[]{Type});
???????4、Bundle對象可以從activity.getIntent().getExtras()中返回。 可見,啟動當前activity 的Intent對象是由getIntent()來找到的。
5、通過Bundle的getString()方法,就可以讀出所要的數據。
這就是Bundle的經典用法,包裹數據放入Intent中,目的在于傳輸數據。