Bundle, 传递数据的包裹

       自己用过一段时间的bundle,但是每次都是写写就完事了,并不是很了解bundle,今天就自己好好看看。

       在Activity之间的通信过程中,intent可以携带数据,每次携带一个键值对,无法一次性带很多,而bundle提供了一个好的打包工具,可以让intent这个信使一下可以携带多条键值对,我们先来看看bundle的类。

     public final class Bundle

  • extends Object
    implements Parcelable, Cloneable
    A mapping from String values to various Parcelable types.
  • 它是一个用来存储键值对的,有四种构造函数
    • Bundle()
      Constructs a new, empty Bundle.
      Bundle(Bundle b)
      Constructs a Bundle containing a copy of the mappings from the given Bundle.
      Bundle(ClassLoader loader)
      Constructs a new, empty Bundle that uses a specific ClassLoader for instantiating Parcelable and Serializable objects.
      Bundle(int capacity)
      Constructs a new, empty Bundle sized to hold the given number of elements.
    一般我们在实际中使用,就是使用第一种,构造空的Bundle,然后加入一些键值对,当然,也可以采用第二种,就是接受其他activity传输过来的Bundle,直接放进去。

  • Bundle的方法有很多,但是主要集中在两个大的方面,就是存取数据,存,以put 开头,可以存入字符,字节,有很多,与之相反,取以get开头,获得相应的value。


    在与intent的配合使用中,首先,建立信使,创建intent,putExtras(Bundle bundle) 向intent中放入需要的“携带”的数据,并且在数据包中用put开头的函数存入自己想存入的数据。
  • public class MainActivity extends ActionBarActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Intent intent = new Intent(this,BundleSecActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("key", "这是发送的bundle信息!!!");
            intent.putExtras(bundle);
            startActivity(intent);
        }
    在另外的activity,获取信使,采用getExtras()方法获得bundle数据包,再从里面获得数据。
  • public class BundleSecActivity extends ActionBarActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_bundle_sec);
    
            TextView showInfo = (TextView) findViewById(R.id.showInfo);
            String show = getIntent().getExtras().getString("key");
            showInfo.setText(show);
        }
    
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值