如何将多个startActivityForResult创建到其他Activity?

时间:2015-08-22 14:22:44

标签: android

在我的MainActivity中,我有这样的代码:

public void toSecondActivity(View v){
        if(condition1){
            Intent it = new Intent(MainActitivy.this,SecondAcitivity.class);
            //put extra
            ......
            startActivityForResult(it,1)
        }
        else if(condition2){
            Intent it = new Intent(MainActitivy.this,SecondAcitivity.class);
            //put extra
            ......
            startActivityForResult(it,2)
        }
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 3) {
        //do something
        }
        else if (resultCode == 4){
        //do some other thing
        }
}

然后在SecondActivity中,我有这段代码:

public void returnToMainAcitivity(View v){
                Intent it = getIntent();
                //put extra
                .........
                it.putExtra("ResourceID", mResourceId);
                setResult(3, it);
                finish();
}

我的问题是,如果使用相同的按钮从条件2启动结果,如何将结果设置为4?

public void returnToMainAcitivity(View v){
                Intent it = getIntent();
                //put extra
                .........
                //Not 3 if started from condition2
                //setResult(3, it);
                setResult(4, it);
                finish();
}

我很擅长意图,所以请教我如何解决这个问题。谢谢;)

2 个答案:

答案 0 :(得分:3)

如果我理解正确,请根据您的条件尝试这样的事情:

Intent it = new Intent(MainActitivy.this,SecondAcitivity.class);
it.PutExtra("StartedFromCondition",1)
startActivityForResult(it,1)

只需阅读额外内容并根据需要返回。

应该注意resultCode通常是-1(RESULT_CANCELED)或0(RESULT_OK),表示失败或成功。如果您希望将数据从第二个活动传递回第一个活动,则应该在返回的意图中将额外数据作为Extras返回。

答案 1 :(得分:3)

只是简单地意图中再传递一个参数(inWhichCondition) &安培;当你发回结果时,只需输入你传递的值。 以下是示例代码。

public void toSecondActivity(View v){
        if(condition1){
            Intent it = new Intent(MainActitivy.this,SecondAcitivity.class);
            //put extra
            intent.PutExtra("inWhichCondition",3);
            startActivityForResult(it,1)
        }
        else if(condition2){
            Intent it = new Intent(MainActitivy.this,SecondAcitivity.class);
            //put extra
            intent.PutExtra("inWhichCondition",4);
            startActivityForResult(it,2)
        }
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 3) {
        //do something
        }
        else if (resultCode == 4){
        //do some other thing
        }
}

&安培;当你重新设置结果时

public void returnToMainAcitivity(View v){
                Intent it = getIntent();
                //put extra

                **setResult(inWhichCondition, it);**
                finish();
}