---
title: "启动另一个Activity并返回结果(附源码)"
author: "AndLi"
date: "2011-10-12T07:58:56Z"
tags: []
categories: ["移动开发"]
slug: "activity"
draft: false
lastmod: "2011-10-11T21:53:14Z"
id: 1190078
url: "https://andli.iteye.com/blog/1190078"
---

启动另一个Activity，并返回一个结果。

使用startActivityForResult()

 

![](http://dl.iteye.com/upload/attachment/568426/a5f85ce5-eab2-35e9-81d1-4922ab9d9a57.png)  ![](http://dl.iteye.com/upload/attachment/568428/6c123842-4865-390a-b3e4-ecabbe1b5830.png)

 

点击上一步的时候，保存下一步页面输入的用户信息

MainActivity.java

 

```
package com.amaker.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

	private EditText username, password;
	private Button b1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}

	private void init() {
		b1 = (Button) findViewById(R.id.Button01);
		b1.setOnClickListener(this);
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bundle b = data.getExtras();
		String str_username = b.getString("username");
		String str_password = b.getString("password");
		username.setText(str_username);
		password.setText(str_password);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.Button01:

			String str_username = username.getText().toString();
			String str_password = password.getText().toString();

			Bundle b = new Bundle();
			b.putString("username", str_username);
			b.putString("password", str_password);

			Intent intent = new Intent(MainActivity.this, NextActivity.class);
			intent.putExtras(b);

			startActivityForResult(intent, 1);
			break;

		default:
			break;
		}

	}

}
```

 

 

NextActivity.java

```
package com.amaker.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NextActivity extends Activity {
	private Button b2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.next);
		b2 = (Button)findViewById(R.id.Button02);
		b2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = getIntent();
				intent.putExtra("abc", "test");
				NextActivity.this.setResult(5, intent);
				NextActivity.this.finish();
			}
		});
		
	}
}
```