Friday, May 19, 2017

Xamarin Forms Toast

I like the toast feature in native Xamarin that displays a message which automatically disappears after a preset time.

Toast.makeText(this, "You have won the Nobel Prize for programming", Toast.LENGTH_LONG).show();

However, there is no equivalent in Xamarin Forms yet. But there are several good plug-ins that will offer similar functionality in different ways. I found Toasts.Forms.Plugin by Adam Pedley and Egor Bogatov. It is documented here.

I'm using PCL so I also need their PCL plugin. In Visual Studio 2017 you use it like this...

Start a new Cross-Platform project (Xamarin.Forms) in C#, call it Toaster, and select the PCL option.


Now open NuGet (Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution"). Click on Browse and enter "Toasts.Forms" in the search terms. You will see two packages.

Click on the first one (Toasts.Forms.Plugin) and Check "Project" in the right panel.




You will need to install it in all your projects because it uses Dependency Services. Click [Install].
Now repeat for Toasts.Forms.Plugin-PCL.

If you open the References nodes in your projects you will see references to Toasts.Forms.Plugin.Abstractions and other necessary references were added automatically.

Using the Toasts plugin is fairly simple. We start by registering the Dependency Service in the platform projects.

For each project add the following to MainActivity.cs or MainPage.xaml.cs
using Xamarin.Forms;
using Plugin.Toasts;

For Android we add the registration at the end of MainActivity.OnCreate like this...

DependencyService.Register<ToastNotification>();
ToastNotification.Init(this);

For iOS and WinPhone you can use the similar...

DependencyService.Register<ToastNotification>();
ToastNotification.Init();

For iOS you also have to request permissions. Here's an example for system version 10.0.

UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
{
    // Deal with the problem
}

Now you can write a simple method in the portable project (perhaps put it in a utility class) to display a toast.
void DisplayToast(String title, String text)
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        var notifier = DependencyService.Get<IToastNotificator>();
        var options = new NotificationOptions()
        {
            Title = title,
            Description = text
        };
        var result = await notifier.Notify(options);
    });
}

And you can easily call the method to display a toast from the portable project like this.

void OnPhoneCall(object sender, EventArgs e)
{
    if (sender == "Nobel Prize Committee")
        DisplayToast("Nobel Prize", "Congratulations - you have won the Nobel Prize for programming");
}



No comments:

Post a Comment