Android基础之startActivityForResult()的用法详解

  package net.conw.intenttest;

  import android.app.Activity;

  import android.content.Intent;

  import android.os.Bundle;

  import android.view.View;

  import android.widget.Button;

  import android.widget.EditText;

  import android.widget.LinearLayout;

  public class MainActivity extends Activity implements View.OnClickListener {

  private EditText editText;

  private Button button;

  public static int REQUEST_CODE = 1;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  LinearLayout layout = new LinearLayout(this);

  editText = new EditText(this);

  button = new Button(this);

  button.setText("Main");

  button.setOnClickListener(this);

  layout.addView(editText);

  layout.addView(button);

  setContentView(layout);

  }

  @Override

  public void onClick(View v) {

  Intent intent = new Intent(this, OtherActivity.class);

  intent.putExtra("text", editText.getText().toString());

  startActivityForResult(intent, REQUEST_CODE);

  }

  @Override

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  super.onActivityResult(requestCode, resultCode, data);

  if(requestCode == REQUEST_CODE && resultCode == OtherActivity.RESULT_CODE) {

  editText.setText(data.getStringExtra("text"));

  }

  }

  }