活動1
創建一個用於參考的類變量。
private final int REQUEST_CODE = 0;
...
//Somewhere in your code you have to call startActivityForResult
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivityForResult(intent);
活動2
結束活性2之前,你必須設置結果確定,將您希望帶回活性1 likeso
Intent data = new Intent();
data.putExtra("name", "Mark");
data.putExtra("number", 1);
data.putExtra("areYouHappy", true);
setResult(RESULT_OK, data);
finish(); //closes Activity2 and goes back to Activity1
數據現在回到Activity1,您應該重寫onActivityResult方法並從Activity2中檢索值。
您首先檢查Activity2的結果是否正確,然後檢查通過的參考REQUEST_CODE。由於之前我們創建了private final int REQUEST_CODE = 0
,因此我們檢查requestCode是否等於變量REQUEST_CODE。如果再從活動2.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK) {
if(requestCode==REQUEST_CODE) {
if(data.getExtras()!=null) {
String name = data.getStringExtra("name");
int number = data.getIntExtra("number",0); //2nd parameter is the default value in case "number" does not exist
boolean areYouHappy = data.getBooleanExtra("areYouHappy", false); //2nd parameter is the default value in case "areYouHappy" does not exist
}
}
}
}
任何建議將被讚賞 – Nitin 2012-04-11 09:51:40
不使用'ActivityGroup'它的棄用,而是使用'Fragment'。 – 2012-04-11 11:17:06
@ Lalit Poptani你能給我一個簡單的例子我怎樣才能使用片段。 – Nitin 2012-04-11 12:12:28