android利用startActivityForResult()方法得到另一个Activity的返回值
第一个Activity
[java]
package yyy.testandroid5;
import android.app.Activity;
import android.content.ComponentName;
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 TestAndroid5Activity extends Activity {
private EditText edit;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//打开第二个Activity
Intent intent = new Intent();
intent.setComponent(new ComponentName("yyy.testandroid6", "yyy.testandroid6.TestAndroid6Activity"));
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra("test", edit.getText().toString());
startActivityForResult(intent, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0){
edit.setText(data.getStringExtra("return"));
}
}
}
第二个Activity
[java]
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;
import android.widget.TextView;
public class TestAndroid6Activity extends Activity {
private TextView text;
private EditText edit;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
String str = getIntent().getStringExtra("test");
edit.setText(str);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//添加给第一个Activity的返回值,并设置resultCode
Intent intent = new Intent();
intent.putExtra("return", edit.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
摘自 Central-Perk的专栏
补充:移动开发 , Android ,