我想知道是否有可能处理来自例如活动1中的活动2和活动3有一个onActivityResult()
,或者每个返回数据的活动是否需要一个方法?
活动1是应用程序的主要活动。
活动1:
// Handle return value from activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
String imageId = data.getExtras().getString("imageId");
// Do something if data return from activity 2 ??
// Do something if data return from activity 3 ??
}
}
活动2
Intent intent = new Intent();
intent.putExtra("imageId", imagePath);
setResult(RESULT_OK, intent);
finish();
活动3
Intent intent = new Intent();
intent.putExtra("contactId", data);
setResult(RESULT_OK, intent);
finish();
答案 0 :(得分:8)
在活动1的startActivityForResult
中设置requestCode:
致电活动2
Intent intent = new Intent(this, Activity2.class);
startActivityForResult(intent,10);
致电活动3
Intent intent = new Intent(this, Activity3.class);
startActivityForResult(intent,11);
现在,当您来onActivityResult
检查requestCode
像:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (10):
{
// do this if request code is 10.
}
break;
case (11):
{
// do this if request code is 11.
}
break;
}
答案 1 :(得分:7)
No confusion check result code and request code
..
示例:
private static final int TWO = 2;
private static final int THREE = 3;
startActivityForResult(new Intent(this,Activity2.class),TWO); // one for Activity 2
startActivityForResult(new Intent(this,Activity3.class),THREE);
和
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK ) {
if(requestCode == TWO) {
// Activity two stuff
} else if(requestCode == THREE) {
// Activity three stuff
}
}
}