一)概述
1.1)发送端用putExtras传递一个Bundle,接收端通过getExtras方法得到一个Bundle,
Bundle可以当成一个包含参数Key,Value的map。
1.2)发送端可以覆盖父类的onActivityResult,接受接收端返回的结果。
二)实例说明,有两个Activity,LoginActivity和MainActivity,
LoginActivity传递UserName和密码给MainActivity,
MainActivity返回ID给LoginActivity
2.1)LoginActivity关键代码
传递参数并且打开MainActivity
Intent intent = new Intent();
Bundle bundle = new Bundle();
//设置参数UserName
bundle.putString("UserName", LoginActivity.this.txtUserName.getText().toString());
//设置参数Password
bundle.putString("Password", LoginActivity.this.txtPassword.getText().toString());
intent.putExtras(bundle);
intent.setClass(LoginActivity.this, MainActivity.class);
//打开窗口MainActivity,并且等待MainActivity返回参数是10000
startActivityForResult(intent, 10000);
接受MainActivity的返回值
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10000) { //startActivityForResult方法设置的传递参数
if (resultCode == 10001) { //MainActivity 返回给LoginActivity的参数
Bundle bundle = data.getExtras();
String id = bundle.getString("ID");
Toast.makeText(this, "用户ID:" + id, Toast.LENGTH_LONG).show();
}
}
}
2.2)MainActivity的关键代码
接受LoginActivity的参数
Bundle bundle = this.getIntent().getExtras();
this.txtUserName.setText(bundle.getString("UserName"));
this.txtPassword.setText(bundle.getString("Password"));
点击按钮返回参数给LoginActivity,注意setResult(10001, intent);中的10001
MainActivity的onActivityResult(int requestCode, int resultCode, Intent data)方法的
参数resultCode会得到这个值
this.btnConfirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
Bundle bundleResult = new Bundle();
bundleResult.putString("ID",MainActivity.this.txtId.getText().toString());
intent.putExtras(bundleResult);
finish();
}
});
LoginActivity和MainActivity完整代码的下载地址:
http://download.csdn.net/detail/songlaf/9773938