Activity startActivityForResult

public void startActivityForResult (Intent intent, int requestCode)
从一个Activity启动另一个activity,得到结果返回给前一个activity。

简单说

OneActivity实现onActivityResult (int requestCode, int resultCode, Intent data)方法,然后使用startActivityForResult启动另一个Activity
另一个Activity取得结果后通过setResult (…)把结果传回。

代码如下

界面代码不提供了,两个都是一个简单的button
注意要在AndroidManifest.xml定义你新增的Activity

<activity android:name=".OtherActivity"></activity>

第一个Activity

package com.fatkun;

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.Toast;

public class OneActivity extends Activity {
	private final int myRequestCode = 1; //请求码
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(OneActivity.this, OtherActivity.class);
				//第二个参数是请求码,会在onActivityResult返回
				startActivityForResult(intent, myRequestCode);
			}
		});
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case myRequestCode:
			if (resultCode == Activity.RESULT_OK) {
				//如果resultCode是RESULT_OK的话,就把内容显示出来。
				Toast.makeText(this, data.getExtras().getString("info"), Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
}

第二个Activity

package com.fatkun;

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 OtherActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.other);
		Button btn = (Button) findViewById(R.id.button1);
		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(OtherActivity.this, OneActivity.class);
				intent.putExtra("info", "我是从OtherActivity返回的数据");
				OnClickListener a = this;
				// 这里的OtherActivity.this是为了得到OtherActivity类的对象,因为现在在button的内部类里面,this指向的是OnClickListener
				OtherActivity.this.setResult(Activity.RESULT_OK, intent);
				OtherActivity.this.finish(); // 结束自己
			}
		});
	}

}
updatedupdated2024-08-302024-08-30