安卓中bundle的使用

Bundle类用作携带数据,它类似于Map,用于存放key-value形式的值,相对于Map,它提供了各种常用类型的putXxx()/getXxx()方法,Bundle的内部实际上是使用了HashMap类型的变量来存放PutXxx()方法存入的值。

 SDK里是这样描述:A mapping from String values to various Parcelable types。它帮助我将数据打包传入intent里面,为使用这些数据提供了便利。


java代码:


  1. protected void onListItemClick (ListView l, View v, int position, long id)
  2. {
  3. super.onListItemClick(l, v, position, id);

  4. //获得选中项的HashMap对象 
  5. HashMap map=(HashMap)lv.getItemAtPosition(position);
  6. String Type=map.get("Type"); 
  7. Intent i=new Intent(this,title.class);
  8. Bundle mBundle=new Bundle();
  9. mBundle.putString("type", Type);
  10. i.putExtras(mBundle);
  11. startActivity(i);
  12. }

复制代码

 

       1、实例化Bundle 一个对象,用putString(标记,数据)来将数据导入到Bundle对象中; 

 2、然后将Bundle对象导入到Intent对象中;

  3、Intent启动另一个activity。

  从intent中读出需要的数据:

java代码:

  1. bundle = getIntent().getExtras(); 
  2. if(bundle!=null)
  3. Type=bundle.getString("type");
  4. if(Type!=null) 
  5. //从数据库依据所选类型读出 文章的Title,保存在cur中 
  6. cur=myDBadapter.getTitle(new String[]{Type});
复制代码


       4、Bundle对象可以从activity.getIntent().getExtras()中返回。 可见,启动当前activity 的Intent对象是由getIntent()来找到的。
  5、通过Bundle的getString()方法,就可以读出所要的数据。

  这就是Bundle的经典用法,包裹数据放入Intent中,目的在于传输数据。

转载于:https://www.cnblogs.com/berylqliu/p/6261506.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值