2 番目のアクティビティを開始する場合は、次のコードを使用します。
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
}
}
}
例 :
したがって、あなたが言った例を開発するために上記のコードを使用するには:
最初のアクティビティでは、2 番目のアクティビティを開始します。
public void ButtonClickedMethod(View v)
{
Intent i = new Intent(this, Second.class);
startActivityForResult(i, 1);
}
次に、2 番目のアクティビティのバック プレス メソッドで、次のコードを使用します。
@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
}
}
}