在Activity中调用另一个Activity时,需要调用startActivity(Intent i), 若需要在调用另外一个Activity的同时传递数据,那么就需要利用android.os.Bundle对象封装数据的能力,将欲传递的数据或参数,通过Bundle来传递不同Intent之间的数据。Bundle对象针对了不同的数据类型提供了许多的方法,例如,传递String类型的数据,使用的方法为Bundle.putString(stringName,stringValue):
而要传递Double类型的数据,使用的方法为Bundle.putDouble(doubleName,doubleValue),如下:bundle.putDouble("height", heightNum);
下面这一段代码是打包数据并传递:
Bundle bundle = new Bundle();
bundle.putString("name", nameStr);
bundle.putDouble("height", heightNum);
intent.putExtras(bundle);
startActivity(intent);
在 Activity2 要如何接收来自 Activity1 传递来的数据呢?试想,在 Activity1 是以 Bundle 封装对象,自然在 Activity2 亦是以 Bundle 的方式解开封装的数据;程序中以 getIntent().getExtras() 方法取得随着 Bundle 对象传递过来的数据。若要由 Bundle 对象中取出数据,则使用 Bundle.getString(stringName) 、 Bundle.getDouble(doubleName) 等相对应的方法即可。
下面这段代码用来解析传递过来的数据:
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
Double height = bundle.getDouble("height");