当您想开始第二个活动时,请使用以下代码:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
当您想回到第一个活动时,请使用以下代码:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
最后在第一个活动中,您可以通过以下方法获取返回值:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
// If there is no result
}
}
}
一个例子 :
因此,对于使用上述代码开发您所说的示例:
在森林活动中开始第二个活动:
public void ButtonClickedMethod(View v)
{
Intent i = new Intent(this, Second.class);
startActivityForResult(i, 1);
}
然后在第二个活动的背压方法中使用以下代码:
@Override
public void onBackPressed()
{
Intent returnIntent = new Intent();
returnIntent.putExtra("result", ((TextView) findViewById(R.id.text)).getText());
setResult(RESULT_OK,returnIntent);
finish();
}
再次在第一个活动中使用此代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
((Button) findViewById(R.id.button1)).setText(result);
}
if (resultCode == RESULT_CANCELED) {
// If there is no result
}
}
}