在Android開(kāi)發(fā)中,startActivityForResult
用于啟動(dòng)一個(gè)新的Activity,并在該Activity完成后返回結(jié)果
startActivityForResult(intent, requestCode)
方法啟動(dòng)新的Activity。requestCode
是一個(gè)整數(shù),用于標(biāo)識(shí)請(qǐng)求。setResult(resultCode, intent)
方法設(shè)置結(jié)果。resultCode
是一個(gè)整數(shù),表示結(jié)果狀態(tài);intent
是一個(gè)包含返回?cái)?shù)據(jù)的Intent對(duì)象。onActivityResult(requestCode, resultCode, data)
方法,以處理返回的結(jié)果。下面是一個(gè)簡(jiǎn)單的示例:
假設(shè)我們有兩個(gè)Activity:MainActivity
和SecondActivity
。在MainActivity
中,我們通過(guò)點(diǎn)擊一個(gè)按鈕來(lái)啟動(dòng)SecondActivity
,并等待其返回結(jié)果。
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
Toast.makeText(this, "Result: " + result, Toast.LENGTH_SHORT).show();
}
}
}
在SecondActivity
中,我們處理完成后,將結(jié)果設(shè)置為一個(gè)字符串,并返回給MainActivity
。
SecondActivity.java:
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("result", "Hello from SecondActivity!");
setResult(RESULT_OK, intent);
finish();
}
});
}
}
當(dāng)用戶(hù)點(diǎn)擊SecondActivity
中的按鈕時(shí),將返回一個(gè)字符串結(jié)果給MainActivity
,并顯示一個(gè)Toast消息。