0

In my Xamarin Forms app, I am using native Android code for the platform. I want to show a AlertDialog.Builder and catch the event when the user taps outside of the dialog box with SetOnCancelListener. This is my code:

AlertDialog.Builder adb = new AlertDialog.Builder(this);

adb.SetTitle("title");

adb.SetItems(myItems.Select(x => x.Name).ToArray(), (s, e) =>
{
    // not important code
});

var cancelled = new CancelListener();
cancelled.Cancelled += (s, e) =>
{
    // not important code
};
adb.SetCancelable(true);
adb.SetOnCancelListener(cancelled);

Dialog d = adb.Create();
d.Show();

My CancelListener class:

public class CancelListener : Java.Lang.Object, IDialogInterfaceOnCancelListener
{
    public event EventHandler Cancelled;

    public IntPtr Handle => IntPtr.Zero;

    public CancelListener() : base()
    {

    }

    public void Dispose()
    {
        Cancelled = null;
    }

    public void OnCancel(IDialogInterface dialog)
    {
        Cancelled?.Invoke(null, EventArgs.Empty);
    }
}

When I tap outside of the dialog box I get the message:

System.NotSupportedException: Unable to activate instance of type MyProject.CancelListener from native handle

Drake
  • 2,679
  • 4
  • 45
  • 88

0 Answers0