Android:不同Activity之间的数据传递

在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");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值