1.Bundle简介:

Bundle主要用于传输数据,它保存的数据,是以key-value的形式存储的。 Bundle常用于在Activity间传递数据 ,当不bundle传递的是对象或对象数组时,必须实现Serializable或Parcelable接口,下面分别介绍bundle在activity间如何传递基本数据类型和对象。

2.传递基本类型

Bundle提供了各种putXxx()/getXxx()方法,用于读写基本数据类型,Bundle用于读写基本数据类型的API有:

示例 写数据的方法:

               Bundle bundle=new Bundle();
               bundle.putString("name","police");
               bundle.putInt("years",8);
               final Intent intent=new Intent().setClassName("police.myapp","police.myapp.Main2Activity");
               intent.putExtras(bundle);
               startActivity(intent);

执行后将bundle绑定到intent,传递到Mian2Activity

读数据的方法: (Intent.getExtras()获取bundle对象)

    Bundle bundle=this.getIntent().getExtras();
      String bundleString=bundle.getString("name");
      int bundleInt=bundle.getInt("years");
      textView.setText(bundleString+bundleInt);

3.传递Parcelable类型的对象

3.1Parcelable说明

Parcelable是Android自定义的一个接口,它包括将数据写入Parcel和从Parcel中读出的API。 一个实体(用类来表示),如果需要封装到Bundle中去,可以通过实现Parcelable接口来完成。

4.传递Serializable类型的对象