startActivityForResult
是Android開發(fā)中用于啟動另一個Activity并期望從該Activity獲取返回結(jié)果的方法。其主要用途和用法如下:
setResult
方法將結(jié)果返回給啟動它的Activity,啟動的Activity通過重寫onActivityResult
方法來接收和處理這些結(jié)果。Intent intent = new Intent(this, TargetActivity.class);
startActivityForResult(intent, REQUEST_CODE);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// 處理返回的數(shù)據(jù)
}
}
Intent intent = this.getIntent();
String result = intent.getStringExtra("result");
setResult(Activity.RESULT_OK, intent);
finish();
假設我們有兩個Activity:MainActivity
和SecondActivity
。在MainActivity
中,用戶可以點擊一個按鈕來啟動SecondActivity
。在SecondActivity
中,用戶可以輸入一些數(shù)據(jù),然后點擊一個按鈕返回結(jié)果到MainActivity
。
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
Intent intent = this.getIntent();
String input = intent.getStringExtra("input");
String result = processData(input); // 假設這是處理數(shù)據(jù)的方法
intent.putExtra("result", result);
setResult(Activity.RESULT_OK, intent);
finish();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
// 處理返回的數(shù)據(jù)
}
}
通過這種方式,startActivityForResult
允許Activity之間進行數(shù)據(jù)交換和結(jié)果傳遞,從而實現(xiàn)更豐富的應用交互。