2

I Have this:

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

I would like this displayalert to be visible for 5 seconds if the user does not choose any option the displayalert disappears

how can i do this?

  • a popup that disappears automatically is called a Toast. There are a number of plugins you can use in Forms to generate one – Jason Jul 28 '20 at 22:56
  • Welcome to SO ! If the reply is helpful, please do not forget to accept it as answer( click the ✔ in the upper left corner of this answer), it will help others who have similar issue. :-) – Junior Jiang Jul 31 '20 at 09:18

1 Answers1

3

Welcome to SO !

Unfortunately , Xamarin Forms not provides some like Dismiss method for alert windown . However , we can use other ways to achieve that . Such as using Xamarin.Forms DependencyService .

First , we can create a IShowAlertService interface in xamarin forms :

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

Next in iOS , Create its implement class :

[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;
        }

}

And in Android , also do that :

[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;
        }
    }
}

Here in Android , need to create a static Instance in MainActivity . Becasue we need to use it in ShowAlertService :

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

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

Now in Xamarin Forms , we can involke it as follow :

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);
}

The effect as follow :

Android

iOS

MC Fer
  • 303
  • 1
  • 2
  • 15
Junior Jiang
  • 12,430
  • 1
  • 10
  • 30