首页 > 解决方案 > DisplayAlert Xamarim 表单

问题描述

我有这个:

var accept = await DisplayAlert("Title", "ask", "yes", "not");

如果用户不选择显示警报消失的任何选项,我希望此显示警报可见 5 秒

我怎样才能做到这一点?

标签: xamarinxamarin.formsxamarin.androidxamarin.iosxamarin-studio

解决方案


欢迎来到 SO!

不幸的是,Xamarin Forms 没有为警报窗口提供一些类似Dismiss的方法。但是,我们可以使用其他方式来实现。例如使用Xamarin.Forms DependencyService

首先,我们可以在 xamarin 表单中创建一个IShowAlertService接口:

public interface IShowAlertService
{
    Task<bool> ShowAlert(string title,string message,string ok, string cancel);
}

接下来在iOS中,创建它的实现类:

[assembly: Dependency(typeof(ShowAlertService))]
namespace XamarinTableView.iOS
{
    class ShowAlertService : IShowAlertService
    {
        TaskCompletionSource<bool> taskCompletionSource;
        public Task<bool> ShowAlert(string title, string message, string ok, string cancel)
        {
            taskCompletionSource = new TaskCompletionSource<bool>();

            var okCancelAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

            //Add Actions
            okCancelAlertController.AddAction(UIAlertAction.Create(ok, UIAlertActionStyle.Default, alert => { 
                Console.WriteLine("Okay was clicked");
                taskCompletionSource.SetResult(true);
            }));
            okCancelAlertController.AddAction(UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, alert => { 
                Console.WriteLine("Cancel was clicked");
                taskCompletionSource.SetResult(true);
            }));

            UIWindow window = UIApplication.SharedApplication.KeyWindow;
            var viewController = window.RootViewController;
            //Present Alert
            viewController.PresentViewController(okCancelAlertController, true, null);

            Device.StartTimer(new TimeSpan(0, 0, 3), () =>
            {
                taskCompletionSource.SetResult(false);

                Device.BeginInvokeOnMainThread(() =>
                {
                    okCancelAlertController.DismissViewController(true,null);
                    // interact with UI elements
                    Console.WriteLine("Auto Dismiss");
                });
                return false; // runs again, or false to stop
            });


            return taskCompletionSource.Task;
        }

}

Android中,也可以这样做:

[assembly: Dependency(typeof(ShowAlertService))]
namespace XamarinTableView.Droid
{
    class ShowAlertService : IShowAlertService
    {
        TaskCompletionSource<bool> taskCompletionSource;

        public Task<bool> ShowAlert(string title, string message, string ok, string cancel)
        {
            taskCompletionSource = new TaskCompletionSource<bool>();

            Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.Instance);
            AlertDialog alert = dialog.Create();
            alert.SetTitle("Title");
            alert.SetMessage("Complex Alert");
            alert.SetButton("OK", (c, ev) =>
            {
                // Ok button click task 
                Console.WriteLine("Okay was clicked");
                taskCompletionSource.SetResult(true);
            });
            alert.SetButton2("CANCEL", (c, ev) => {
                Console.WriteLine("Cancel was clicked");
                taskCompletionSource.SetResult(false);
            });
            alert.Show();

            Device.StartTimer(new TimeSpan(0, 0, 3), () =>
            {
                if (taskCompletionSource.Equals(null))
                    taskCompletionSource.SetResult(false);

                Device.BeginInvokeOnMainThread(() =>
                {
                    alert.Dismiss();
                    // interact with UI elements
                    Console.WriteLine("Auto Dismiss");
                });
                return false; // runs again, or false to stop
            });

            return taskCompletionSource.Task;
        }
    }
}

这里在 Android 中,需要InstanceMainActivity中创建一个静态。因为我们需要在ShowAlertService

public class MainActivity : FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }  

    protected override void OnCreate(Bundle savedInstanceState)
    {
        // ...
        Instance = this;
    }
    //...
}

现在在 Xamarin Forms 中,我们可以按如下方式调用它:

private async void Button_Clicked(object sender, EventArgs e)
{
    bool value = await DependencyService.Get<IShowAlertService>().ShowAlert("Alert", "You have been alerted", "OK", "Cancel");

    Console.WriteLine("Value is : "+value);
}

效果如下:

安卓

iOS


推荐阅读