Displaying toasts in Xamarin.Forms

April 2nd 2021 Xamarin

Toasts are a common way to non-intrusively show information to the user. Unfortunately, there's no built-in control for them in Xamarin.Forms. I also couldn't find a dedicated third-party library with a customizable cross-platform implementation. So I ended up implementing them using the more general-purpose Rg.Plugins.Popup library.

I created a regular popup page that contained only a bottom-aligned toast rendered using built-in Xamarin.Forms controls:

<StackLayout VerticalOptions="End"
                Padding="16">
    <Frame BackgroundColor="LightGreen">
        <Label Text="{Binding Message}" />
    </Frame>
</StackLayout>

The appearance already matched my requirements.

Toast popup appearance

But I still had to customize the behavior to make it a toast. I needed to change a couple of PopupPage properties for that:

  • A semi-transparent dark background shouldn't cover the rest of the page while the toast was visible, so I made page background transparent:

    <pages:PopupPage BackgroundColor="Transparent"
    
  • The toast shouldn't close when tapping elsewhere on the page, so I disabled this feature:

    <pages:PopupPage CloseWhenBackgroundIsClicked="False"
    
  • It should still be possible to interact with the application while the toast was visible, so I made the page background input transparent:

    <pages:PopupPage BackgroundInputTransparent="True"
    

The only thing left was to create a simple wrapper method for showing the toast and hiding it automatically after some time:

public static async Task Show(string message, int millisecondsDuration = 2000)
{
    await PopupNavigation.Instance.PushAsync(new ToastPage(message));

    _ = Task.Delay(millisecondsDuration)
        .ContinueWith(async _ => await PopupNavigation.Instance.PopAsync());
}

Intentionally, the task completes as soon as the toast appears. That's the end of the operation. We don't care when it closes.

Showing a toast from the code is now as easy as calling and awaiting this method:

await ToastPage.Show("Operation succeeded!")

You can find a working example in my GitHub repository.

Since Xamarin.Forms doesn't have a built-in toast control and I couldn't find a third party library with one custimizable enough for my needs, I implemented toasts as popups. The sample implementation is pretty simple but can be further customized as needed, including different animations.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License