歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發中Bundle用法 包裹數據

Android開發中Bundle用法 包裹數據

日期:2017/3/1 11:08:10   编辑:Linux編程

SDK裡是這樣描述:A mapping from String values to various Parcelable types。

  它幫助我將數據打包傳入intent裡面,為使用這些數據提供了便利。

  protected void onListItemClick (ListView l, View v, int position, long id)

  {

   super.onListItemClick(l, v, position, id);

   //獲得選中項的HashMap對象

   HashMap<String,String> map=(HashMap<String,String>)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中讀出需要的數據:

  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中,目的在於傳輸數據。

Copyright © Linux教程網 All Rights Reserved