Xamarin.Android中使用TaskCompletionSource创建阻塞式的对话框

代码如下

using Android.OS;
using Android.Views; 
using Android.Util; 
using Activity = Android.App.Activity;

namespace KangHuiXinCai_FangDai_AndroidScanner
{
    public class Dialog_SettingPassword : Dialog
    {  
        TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();
        public Dialog_SettingPassword(Activity context, string mailName, bool retry) : base(context)
        { 
            this.OwnerActivity = context; 
        }

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            //隐藏自带标题
            this.RequestWindowFeature((int)WindowFeatures.NoTitle);
            this.SetCanceledOnTouchOutside(false);
            SetContentView(Resource.Layout.dlg_SettingPassword);

            //宽高
            var windowManager = this.OwnerActivity.WindowManager;//.WindowManager;
            DisplayMetrics displayMetrics = new DisplayMetrics();
            windowManager.DefaultDisplay.GetMetrics(displayMetrics);
            Window.SetLayout(displayMetrics.WidthPixels, displayMetrics.HeightPixels / 2);

            //事件
            FindViewById<Button>(Resource.Id.btnCancel).Click += (sender, e) =>
            {
                EndDialog(DialogResult.Cancel);
            };

            FindViewById<Button>(Resource.Id.btnOk).Click += (sender, e) =>
            {
                EndDialog(DialogResult.Ok);
            };
        }

        public void EndDialog(DialogResult result)
        {   
            tcs.SetResult(result); 
            Dismiss();
        }

        public async Task<DialogResult> ShowDialog()
        { 
            Show(); 
            var res = await tcs.Task;
            return res; 
        }
    }

    public enum DialogResult
    {
        Ok,
        Cancel,
    }
}

主要代码

  • 创建TaskCompletionSource

TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();

  • 使用它来等待返回结果

var res = await tcs.Task;

return res;

  • 设置它的返回结果

tcs.SetResult(result);

 

posted @ 2024-01-30 08:50  法宝  阅读(15)  评论(0编辑  收藏  举报