很多的时候不单单进行Activity跳转,而是在进行Activity跳转的同时传递数据,这里就可以利用Android.os.Bundle对象封闭数据的能力,将所要传递的数据或参数通过Bundle来传递不同Activity间的数据。举个例子来说明:从当前Activity跳转到下一个Activity的同时,并传入一个double型参数、一个String型参数(MainActivity--->NextActivity的跳转)
在MainActivity.java中的代码如下:
Intent intent = new Intent();
//实现activity之间的跳转
intent.setClass(MainActivity.this, NextActivity.class);
//创建Bundle对象,并封装数据
Bundle bundle = new Bundle();
double height = 1.74;
String name = "lilei";
bundle.putDouble("height", height);
bundle.putString("name", name);
intent.putExtras(bundle);
//开启跳转
startActivity(intent);
有一方发送参数,就必然有一方要接受参数。在NextActivity.java中实现接受,代码如下:
//创建Bundle对象
Bundle bundle = NextActivity.this.getIntent().getExtras();
//获得接受参数键值
double height = bundle.getDouble("height");
String name = bundle.getString("name");
String str = "name="+name+", height="+height;
//String str = "this is ok";
Toast.makeText(NextActivity.this, str, Toast.LENGTH_SHORT).show();
运行效果截图: