Search code examples
androidxamarinxamarin.androidandroidx

How to pass request code in ActivityResultLauncher


I am updating some Xamarin.Android code to use the newer AndroidX APIs. The old way to launch an activity in my project was like this:

var intent = new Intent(this.Activity, typeof(SomeActivity));
intent.PutExtra("someVariableA", a);
intent.PutExtra("someVariableB", b);
StartActivityForResult(intent, 0);

The new way is with ActivityResultLauncher object:

activityResultLauncher.Launch(intent);

But how do I pass the request code? (second parameter in StartActivityForResult)


Solution

  • First you do not need onActivityResult(). That way was old.You now have launchers for specific purposes.Create a function like this:

    ActivityResultLauncher<String> imageActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                uri -> 
                   //do something with uri
                });
    

    And you want to launch this, just write:

    imageActivityResultLauncher.launch("image/*");
    

    For more details refer

    https://stackoverflow.com/a/63654043/12555686