我创建了一个AlertDialog.Builer,第二次显示弹出窗口并与之交互时出现错误。
我创建了这样的对话框:
public Task<bool?> ShowAsync(string title, string message, string okContent = null, string cancelContent = null, bool okBeforeCancel = false)
{
if (_tcs is null)
{
_tcs = new TaskCompletionSource<bool?>();
}
if (_dialog != null)
{
Dismiss();
}
var alertBuilder = BuildAlertView(title, message, okContent, cancelContent, _tcs, okBeforeCancel);
_dialog = alertBuilder.Create();
_dialog.Show();
return _tcs.Task;
}
private static AlertDialog.Builder BuildAlertView(string title, string message, string ok, string cancel, TaskCompletionSource<bool?> tcs, bool okBeforeCancel)
{
var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
var builder = new AlertDialog.Builder(mvxTopActivity.Activity)
.SetCustomTitle(CreateTitle(title, mvxTopActivity))
.SetMessage(message)
.SetCancelable(false);
AddButtons(builder, tcs, ok, cancel, okBeforeCancel);
return builder;
}
private static void AddButtons(AlertDialog.Builder builder, TaskCompletionSource<bool?> tcs, string ok, string cancel, bool okBeforeCancel)
{
(ok, cancel) = okBeforeCancel ? (cancel, ok) : (ok, cancel);
var (okResult, cancelResult) = okBeforeCancel ? (false, true) : (true, false);
if (!IsNullOrWhiteSpace(ok))
{
builder.SetCancelable(false);
builder.SetPositiveButton(ok, (s, e) =>
{
tcs.SetResult(okResult);
});
}
if (!IsNullOrWhiteSpace(cancel))
{
builder.SetCancelable(true);
builder.SetNegativeButton(cancel, (s, e) =>
{
tcs.SetResult(cancelResult);
});
}
}
我第一次显示弹出窗口时,一切都会按预期进行。第二次,它在tcs.SetResult()方法时崩溃。
答案 0 :(得分:0)
根据我的评论,这应该可以解决您遇到的问题。
public Task<bool?> ShowAsync(Activity activity, string title, string message, string okContent = null, string cancelContent = null, bool okBeforeCancel = false)
{
if (_tcs is null)
{
_tcs = new TaskCompletionSource<bool?>();
}
if (_dialog != null)
{
Dismiss();
}
activity.RunOnUiThread(()=>{
var alertBuilder = BuildAlertView(title, message, okContent, cancelContent, _tcs, okBeforeCancel);
_dialog = alertBuilder.Create();
_dialog.Show();
});
return _tcs.Task;
}