android - 在 AlertDialog 中的 TaskCompletionSource 上设置结果时出错
问题描述
我创建了一个 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() 方法处崩溃。
解决方案
根据我的评论,这应该有助于解决您遇到的问题。
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;
}
推荐阅读
- c++ - 使用鼠标滚动的 QKeySequence
- javascript - React 组件从 props 动态渲染 SVG
- json - 消费时反序列化 JSON 消息期间的问题 (NPE)
- mysql - Mysql全文搜索和整数字段查询降低性能极端
- jenkins - 使用 Jenkins 将 Flyway 集成到现有数据库中
- node.js - 令牌过期时中间件未正确重定向到登录页面
- sql - 设置参数后存储过程中的 WITH RECOMPILE
- python - Python Logger 无法写入文件?
- testing - 如何在搜索功能中手动测试数据保留要求?
- c++ - 使用带有缓冲区的 std::span - C++