两个 Activity 跳转,都是在第一个 Activity 调用 startActivity() 方法启动第二个 Activity ,然后在第二个 Activity 调用 Context.finish() 方法实现返回到第一个 Activity 。但是有的时候业务需求很复杂,从第二个 Activity 返回到第一个 Activity 时候,需要再次处理某些事情时就要使用 startActivityForResult() 方法启动第二个 Activity 了,并在第一个 Activity 中重写 onActivityResult() 方法。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
userid = (EditText) findViewById(R.id.userid);
pwd = (EditText) findViewById(R.id.password);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (userid.getText().toString().equals("tony")
&& pwd.getText().toString().equals("1")) {
Intent it = new Intent(LoginActivity.this,
SuccessActivity.class);
it.putExtra("userid", userid.getText().toString());
startActivityForResult(it, 1);
} else {
Intent it = new Intent(LoginActivity.this,
FailureActivity.class);
startActivityForResult(it, 2);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
// 登录成功之后返回的。
Log.v(TAG, "from success activity return. resultCode=" + resultCode);
break;
case 2:
// 登录失败之后返回的。
Log.v(TAG, "from failure activity return. resultCode=" + resultCode);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
成功屏幕 SuccessActivity
public class SuccessActivity extends Activity {
Button btnBack;
TextView label;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
label = (TextView) findViewById(R.id.label);
Bundle bundle = this.getIntent().getExtras();
String userid = bundle.getString("userid");
label.setText(userid);
btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(4, (new Intent()).putExtra("name", label.getText()
.toString()));
SuccessActivity.this.finish();
}
});
}
}
失败屏幕 FailureActivity
public class FailureActivity extends Activity {
Button btnBack ;
TextView label;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.failure);
label = (TextView)findViewById(R.id.label);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(5);
FailureActivity.this.finish();
}
});
}
}