如何区分两个StartActivityFor Result()

时间:2017-04-17 01:09:44

标签: android

我有两个听众

fromCityTrain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(getActivity(),train_autocomplete.class);
            startActivityForResult(i, 2);
        }
    });

    toCityTrain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(getActivity(),train_autocomplete.class);
            startActivityForResult(i, 3);
        }
    });

两者都会进行相同的活动。现在当我返回数据时,我怎么知道哪个人调用了它。

这是train_autocomplete.class

中的内容
Intent intent=new Intent();

            intent.putExtra("stationCode",stationCode);
            intent.putExtra("stationName",stationName);
            setResult(2,intent);
            finish();

1 个答案:

答案 0 :(得分:0)

onActivityResult将为您提供requestCode。在您的示例中,第一个案例为2,第二个案例为3

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 2:
        // fromCityTrain
        if(resultCode==2) Log.i("TAG", "resultCode 2 returned from activity");
        else Log.i("TAG", "resultCode "+ resultCode +" returned from activity");
        break;
    case 3:
        // toCityTrain
        if(resultCode==2) Log.i("TAG", "resultCode 2 returned from activity");
        else Log.i("TAG", "resultCode "+ resultCode +" returned from activity");
        break;
    }
}