Xamarin.Android迁移AndroidX:如何在ActivityResultLauncher中传递请求码?
解决Xamarin.Android中ActivityResultLauncher传递请求码的问题
在AndroidX的Activity Result API里,请求码不再通过Launch方法直接传递,可以通过以下两种方式处理原请求码的区分需求:
1. 为不同请求创建独立的ActivityResultLauncher
如果不同请求需要各自的结果处理逻辑,最直接的方案是为每个原请求码单独注册一个ActivityResultLauncher,每个Launcher对应一组请求与结果逻辑:
// 声明对应原请求码0的Launcher private ActivityResultLauncher<Intent> _request0Launcher; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // 初始化Launcher并绑定结果处理逻辑 _request0Launcher = RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), result => { if (result.ResultCode == Result.Ok) { Intent data = result.Data; // 这里处理原请求码0对应的返回结果 } }); } // 启动Activity时调用对应Launcher var intent = new Intent(this, typeof(SomeActivity)); intent.PutExtra("someVariableA", a); intent.PutExtra("someVariableB", b); _request0Launcher.Launch(intent);
2. 通过Intent传递自定义标识替代请求码
如果不想创建多个Launcher,可以在Intent中添加自定义额外参数模拟请求码的作用,在结果回调中读取该参数区分不同请求:
// 声明通用Launcher private ActivityResultLauncher<Intent> _generalLauncher; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _generalLauncher = RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), result => { if (result.Data != null) { int customRequestCode = result.Data.GetIntExtra("CustomRequestCode", -1); // 根据自定义标识区分处理逻辑 switch(customRequestCode) { case 0: // 处理原请求码0的逻辑 break; case 1: // 处理原请求码1的逻辑 break; } } if (result.ResultCode == Result.Ok) { // 通用结果处理逻辑 } }); } // 启动时添加自定义请求标识 var intent = new Intent(this, typeof(SomeActivity)); intent.PutExtra("someVariableA", a); intent.PutExtra("someVariableB", b); // 添加自定义请求码参数 intent.PutExtra("CustomRequestCode", 0); _generalLauncher.Launch(intent);
核心说明
AndroidX的Activity Result API设计初衷就是替代传统的请求码机制,官方更推荐用多个独立Launcher来区分不同请求场景,既避免请求码冲突,也让代码逻辑更清晰。若需复用Launcher,就通过Intent额外参数传递自定义标识来模拟请求码的作用。
内容的提问来源于stack exchange,提问作者Drake
相关产品推荐
相关产品推荐

