Friday, July 4, 2014

OnActivityResult not called for Fragment


If you have an activity that hosts a fragment that opens another activity with StartActivityForResult the fragment doesn't get OnActivityResult called, but the hosting activity does.

From my research, the hosting activity should get called first and then the active fragment.

This does not seem to work in Xamarin at the moment. If anyone knows anything about this, please leave a comment. I'll try to get a question up on stack overflow later on today... :)

Some code

In my fragment

   Activity.StartActivityForResult(typeof(MyCoolNewActivity), 0);

And in the new activity

    Intent output = new Intent();
    output.PutExtra("meaningOfLife", 42);
    SetResult(Result.Ok, output);
            
    Finish();


And in the hosting activity

      protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if (requestCode == 0
    {
var fragment = SupportFragmentManager.FindFragmentByTag("MyFragment") as MyFragment;
        if (fragment != null)
        {
             var mol = data.GetIntExtra("meaningOfLife", 0);
             fragment.SetMeaningOfLife(mol);
        }
    }
            
    base.OnActivityResult(requestCode, resultCode, data);
}


No comments:

Post a Comment