自己用过一段时间的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的方法有很多,但是主要集中在两个大的方面,就是存取数据,存,以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); } }