为什么resultCode在changeActivityForesult中返回0

时间:2019-04-24 04:45:29

标签: android

我有3个活动:A,B,C。拥有按钮nextB,这是A中的代码

class A extends AppCompatActivity {
...
  nextB.setOnClickListener(...
    Intent in = new Intent(A.this, B.class);
    startActivityForResult(in, 8);
  );

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8 && resultCode == 9) {
            Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
        }
    }
}

B有两个按钮:nextCresetB。这是B中的代码:

class B extends AppCompatActivity {
    ...
      nextC.setOnClickListener(...
        Intent in = new Intent(B.this, C.class);
        startActivityForResult(in, 9);
      );
      resetB.setOnClickListener(...
        Intent in = new Intent(B.this, B.class);
        startActivityForResult(in, 8);
        finish();
      );
      
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
              if (requestCode == 9 && resultCode == 10) {
                Intent intent = new Intent();
                setResult(9, intent);
                finish();
              }
        }
    }

,在C中,我有按钮finished。这是C中的代码

class C extends AppCompatActivity {
...
  finished.setOnClickListener(...
    Intent intent = new Intent();
    setResult(10, intent);
    finish();
  );   
}

当我从A切换屏幕时,跟随一个nextB-> nextC(单击B)-> finished C移至A并显示祝酒。

但是当我切换屏幕时,请跟随两个nextB-> resetB(单击B)-> nextC(单击B)-> finished C将移至A,但不会显示敬酒。 当我在A中调试resultCode时返回0。 我尝试在单击finish()时删除resetB,但它返回相同的结果(在A中不显示“确定”对话框。)

在这里发生了什么以及如何在跟随屏幕切换屏幕时显示对话框? 非常感谢!

1 个答案:

答案 0 :(得分:0)

仅在活动A中调用一个结果

class A extends AppCompatActivity {
    ...
      nextB.setOnClickListener(...
        Intent in = new Intent(A.this, B.class);
        startActivityForResult(in, 8);
      );

        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(resultCode == RESULT_OK){
            if (requestCode== 8) {
                Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
                   }


        }
    }

在b中使用StartActivityForwardResult到C,并在重置B按钮“赞”按钮中设置结果

 resetB.setOnClickListener(...
        Intent intent = new Intent();
    setResult(RESULT_OK, intent);
    finish();
      );

nextC.setOnClickListener(
        Intent in = new Intent(B.this, C.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
                                    startActivity(intent);

        );

和C活动集结果代码与您在A活动中定义的代码相同

class C extends AppCompatActivity {
...
  finished.setOnClickListener(...
    Intent intent = new Intent();
    setResult(RESULT_OK, intent);
    finish();
  );   
}