我的 Xamarin.Android 应用程序有一个关于 IDialogInterfaceOnDismissListener
的问题。
我的重现样本:
public enum ConfirmationResult
{
Cancel,
Yes,
No
}
public interface IDialogService
{
Task<ConfirmationResult> ConfirmAsync(string title, string message, string acceptText, string declineText);
}
public class DialogService : IDialogService
{
class DismissDelegateListener : IDialogInterfaceOnDismissListener, IDialogInterfaceOnCancelListener
{
private Action _callback;
public DismissDelegateListener()
{
}
public DismissDelegateListener(Action callback)
{
_callback = callback;
}
public void Dispose()
{
_callback = null;
}
public IntPtr Handle { get; }
public void OnCancel(IDialogInterface dialog)
{
_callback?.Invoke();
}
public void OnDismiss(IDialogInterface dialog)
{
_callback?.Invoke();
}
}
private readonly WeakReference<Context> _activity;
public DialogService(Context activity)
{
_activity = new WeakReference<Context>(activity);
}
public async Task<ConfirmationResult> ConfirmAsync(string title, string message, string acceptText, string declineText)
{
Context target;
if (!_activity.TryGetTarget(out target))
return ConfirmationResult.Cancel;
TaskCompletionSource<ConfirmationResult> tcs = new TaskCompletionSource<ConfirmationResult>();
var builder = new AlertDialog.Builder(target);
var d = builder
.SetTitle(title)
.SetMessage(message)
.SetPositiveButton(acceptText, (sender, args) =>
{
tcs.SetResult(ConfirmationResult.Yes);
(sender as AlertDialog)?.Dispose();
})
.SetNegativeButton(declineText, (sender, args) =>
{
tcs.SetResult(ConfirmationResult.No);
(sender as AlertDialog)?.Dispose();
})
// if this line is uncommented my application crashes once the dialog is opened
// .SetOnCancelListener(new DismissDelegateListener(() => { tcs.SetResult(ConfirmationResult.Cancel); }))
.Create();
d.Show();
return await tcs.Task;
}
}
只要我调用 SetOnCancelListener
,我的应用程序就会崩溃并显示错误消息 System.InvalidCastException: Specified cast is not valid.
对我来说,一切似乎都是正确的——我正在传递所请求接口(interface)的实现,而且我的实现也不是那么困难。
这个问题是否给任何人敲响了警钟?
最佳答案
从 Java.Lang.Object 派生是解决方案。
class DismissDelegateListener : Java.Lang.Object, IDialogInterfaceOnDismissListener, IDialogInterfaceOnCancelListener
//class DismissDelegateListener : IDialogInterfaceOnDismissListener, IDialogInterfaceOnCancelListener
{
private Action _callback;
public DismissDelegateListener()
{
}
public DismissDelegateListener(Action callback)
{
_callback = callback;
}
protected override void Dispose(bool disposing)
{
_callback = null;
base.Dispose(disposing);
}
public void OnCancel(IDialogInterface dialog)
{
_callback?.Invoke();
}
public void OnDismiss(IDialogInterface dialog)
{
_callback?.Invoke();
}
}
关于android - 如何在我的应用程序不崩溃的情况下传递 DialogInterface OnDismissListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39512472/