Skip to content

Instantly share code, notes, and snippets.

@suchithm
Created February 22, 2022 12:37
Show Gist options
  • Save suchithm/56000751f08bbcfb9843b0c5d8962338 to your computer and use it in GitHub Desktop.
Save suchithm/56000751f08bbcfb9843b0c5d8962338 to your computer and use it in GitHub Desktop.
Handling StartActivityForResult | OnActivityResult Deprecated in Xamarin Android
using AndroidX.Activity.Result;
using AndroidX.Activity.Result.Contract;
[Activity(Label = "EditImageActivity", MainLauncher = false)]
public class MyActivity : Activity
{
private ActivityResultCallback _activityResultCallback;
private ActivityResultLauncher _activityResultLauncher;
public static int _requestCode;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
_activityResultCallback = new ActivityResultCallback(this);
_activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), _activityResultCallback);
}
private void OpenGallery()
{
//var galleryIntent =.. //create your intent
_requestCode = "1001"; //flag to handle the multiple intent request
_activityResultLauncher.Launch(galleryIntent);
}
public void MyActivityResultReceived( int resultCode, Intent data)
{
if ((_requestCode == "1001") || (resultCode == (int)Result.Ok))
{
//handle the result
}
}
class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
MyActivity _myActivity;
public ActivityResultCallback(NotesFragment myActivity)
{
_myActivity = myActivity; //initialise the parent activity/fragment here
}
public void OnActivityResult(Java.Lang.Object result)
{
var activityResult = result as ActivityResult;
_myActivity.MyActivityResultReceived(activityResult.ResultCode, activityResult.Data); //pass the OnActivityResult data to parent class
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment