3

Usually with Android, you set an integer result code when setting the result of an activity as shown here:

void setResult(int resultCode)

Xamarin, instead, requires an enum defined as Android.App.Result. This enum has these values:

Ok, Canceled, FirstUser

The Problem

You cannot set custom result codes in Xamarin Android. FirstUser is supposed to define the first safe custom result for the user to use. i.e, any integer greater than the value of FirstUser is fine to use as stated here in the Android docs.

I am forced to set the result code as this enum type. Is there a way around this? The OnActivityResult method also uses this enum.

protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data)

Sam Liddle
  • 158
  • 1
  • 7
  • Why did you need set custom result code? Could you please elaborate a bit more? – York Shen Feb 01 '18 at 08:06
  • @YorkShen-MSFT Yes thank you. I am fairly new to C# and didn't realise the following was the case: https://stackoverflow.com/a/6413841/5504424 – Sam Liddle Feb 07 '18 at 21:41

1 Answers1

2

I am forced to set the result code as this enum type. Is there a way around this?

As you said, we can't custom the result codes. If you need to identify which Activity's SetResult method fire the OnActivityResult() method in MainActivity, here is a workaround:

In MainActivity, open ResultActivity1:

Intent intent = new Intent(this, typeof(ResultActivity1));
StartActivityForResult(intent, 1);

In ResultActivity1, set the result:

Intent intent = new Intent();
intent.PutExtra("name", "ResultActivity1");
SetResult(Result.Ok, intent);
Finish();

In MainActivity OnActivityResult method:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    if(resultCode == Result.Ok)
    {
        if(requestCode == 1)
        {
            var name = data.GetStringExtra("name");
            if (name == "ResultActivity1")
            {
                Toast.MakeText(this, name, ToastLength.Short).Show();
            }
        }
    }
    base.OnActivityResult(requestCode, resultCode, data);
}
York Shen
  • 9,014
  • 1
  • 16
  • 40
  • 1
    This was my first thought but it turns out that you can just use an invalid cast of the enum. `int myResultCode = 25432;` `SetResult((Android.App.Result)myResultCode, ...);` `protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data) { if ((int)resultCode == myResultCode) {...} }` – Sam Liddle Feb 08 '18 at 10:01
  • @SamLiddle, could you please post the answer so that someone else who have encounter the problem can see the answer? :) – York Shen Feb 08 '18 at 11:46