Android之startActivityForResult过时升级替换

首先需要androidx.activity:activity的版本大于1.2.0才能使用launch替换。

修改build.gradle下的依赖库为1.3.0或以上版本。

implementation 'androidx.appcompat:appcompat:1.4.0'

A页面跳转

private ActivityResultLauncher launcher;

Intent intent = new Intent(this, B.class);
intent.putExtra("data", "传递数据");
launcher.launch(intent);

B页面接收值

String data = getIntent().getStringExtra("data");

B页面点击或返回结束页面

Intent intent = new Intent();
intent.putExtra("result","回调数据");
setResult(Activity.RESULT_OK,intent);
finish();

A页面回调接收数据

launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == Activity.RESULT_OK){
                    String data = result.getData().getStringExtra("result");
                }
            }
        });

你可能感兴趣的:(Android,setResult,跳转传值,回调)