Xamarin.Forms - How To Make Toast Message Using Dependency Service

Introduction

This article demonstrates how to make Toast Message or local message using Dependency Service in Xamarin.Forms applications.
 
Android Output 
 
 
 
UWP Output
 
 
Requirements
  • Visual Studio 2017 update
  • This article was prepared by a windows machine
  • This sample project is targeted for Android, IOS, UWP and tested for Android and UWP 
Let's start!
 
Step 1

You can create a new Xamarin.Forms app by going to File >> New >> Visual C# >> Cross Platform >>Cross Platform App(Xamarin.Forms or Xamarin.Native) and click OK.
 
(Eg - Project name - ToastMessage)  
 
 
Step 2

 After the project creation, add a new Toast Interface in Xamarin.Forms PCL project. For that, go to Solution Explorer >>click ToastMessage(PCL) project >> right click to select Add >> followed by select New Item >> Select Interface >> give the name as Toast and click ok. Here is the code for this interface.
 
C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. namespace ToastMessage  
  6. {  
  7.     public interface Toast  
  8.     {  
  9.         void Show(string message);  
  10.     }  
  11. }  
Step 4

Now, open MainPage.Xaml. For that, go to Solution Explorer >> ToastMessage(PCL) >> double-click to open design view of MainPage.xaml and the cCode is given below.
 
Xaml Code
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:ToastMessage"  
  5.              x:Class="ToastMessage.MainPage">  
  6.   
  7.     <Button Text="Get Toast"   
  8.             HorizontalOptions="Center"  
  9.             VerticalOptions="Center"  
  10.             FontSize="Medium"  
  11.             x:Name="ToastButton"/>  
  12.   
  13. </ContentPage>  
Step 5

Next, go to MainPage.xaml.cs . For that, go to Solution Explorer >>ToastMessage(PCL) >> click open MainPage.xaml.cs and add the following code.
 
C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7.   
  8. namespace ToastMessage  
  9. {  
  10.     public partial class MainPage : ContentPage  
  11.     {  
  12.         public MainPage()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.   
  17.         protected override void OnAppearing()  
  18.         {  
  19.             ToastButton.Clicked += ToastButton_Clicked;  
  20.         }  
  21.   
  22.         private void ToastButton_Clicked(object sender, EventArgs e)  
  23.         {  
  24.             DependencyService.Get<Toast>().Show("Toast Message");  
  25.         }  
  26.     }  
  27. }  
Step 6 

Open Solution Explorer >> ToastMessage(PCL) >>right click and select New Item. In the popup window, select Cross Platform >>Class. This way, you can add a new class.
 
Platform specific implementation
 
Xamarin.Android

In this step, create a new class named Toast_Android and add the following code.

C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.CompilerServices;  
  5. using System.Text;  
  6.   
  7. using Android.App;  
  8. using Android.Content;  
  9. using Android.OS;  
  10. using Android.Runtime;  
  11. using Android.Views;  
  12. using Android.Widget;  
  13. using ToastMessage.Droid;  
  14.   
  15. [assembly: Xamarin.Forms.Dependency(typeof(Toast_Android))]  
  16.   
  17. namespace ToastMessage.Droid  
  18. {  
  19.     public class Toast_Android : Toast  
  20.     {  
  21.         public void Show(string message)  
  22.         {  
  23.             Android.Widget.Toast.MakeText(Android.App.Application.Context,message,ToastLength.Long).Show();  
  24.         }  
  25.     }  
Xamarin.IOS

Now, add another class named Toast_IOS and here is code for this class.
 
C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.CompilerServices;  
  5. using System.Text;  
  6.   
  7. using Foundation;  
  8. using ToastMessage.iOS;  
  9. using UIKit;  
  10.   
  11. [assembly:Xamarin.Forms.Dependency(typeof(Toast_IOS))]  
  12.   
  13. namespace ToastMessage.iOS  
  14. {  
  15.     public class Toast_IOS : Toast  
  16.     {  
  17.         const double LONG_DELAY = 3.5;  
  18.          
  19.   
  20.         NSTimer alertDelay;  
  21.         UIAlertController alert;  
  22.   
  23.         public void Show(string message)  
  24.         {  
  25.             ShowAlert(message, LONG_DELAY);  
  26.         }  
  27.           
  28.   
  29.         void ShowAlert(string message, double seconds)  
  30.         {  
  31.             alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>  
  32.             {  
  33.                 dismissMessage();  
  34.             });  
  35.             alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);  
  36.             UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, truenull);  
  37.         }  
  38.         void dismissMessage()  
  39.         {  
  40.             if (alert != null)  
  41.             {  
  42.                 alert.DismissViewController(truenull);  
  43.             }  
  44.             if (alertDelay != null)  
  45.             {  
  46.                 alertDelay.Dispose();  
  47.             }  
  48.         }  
  49.           
  50.     }  
  51. }  
Xamarin.UWP

Similarly, create another class named Toast_UWP and insert the code  given below.
 
C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Windows.Data.Xml.Dom;  
  7. using Windows.UI.Notifications;  
  8. using ToastMessage.UWP;  
  9.   
  10.   
  11. [assembly:Xamarin.Forms.Dependency(typeof(Toast_UWP))]  
  12. namespace ToastMessage.UWP  
  13. {  
  14.     class Toast_UWP : Toast  
  15.     {  
  16.         public void Show(string message)  
  17.         {  
  18.             ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText01;  
  19.             XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);  
  20.   
  21.             XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");  
  22.             toastTextElements[0].AppendChild(toastXml.CreateTextNode(message));  
  23.               
  24.             XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");  
  25.             ((XmlElement)toastImageAttributes[0]).SetAttribute("src""ms-appx:///Assets/Logo.scale-240.png");  
  26.             ((XmlElement)toastImageAttributes[0]).SetAttribute("alt""logo");  
  27.   
  28.             IXmlNode toastNode = toastXml.SelectSingleNode("/toast");  
  29.             ((XmlElement)toastNode).SetAttribute("duration""short");  
  30.   
  31.             var toastNavigationUriString = "#/MainPage.xaml?param1=12345";  
  32.             var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast"));  
  33.             toastElement.SetAttribute("launch", toastNavigationUriString);  
  34.   
  35.             ToastNotification toast = new ToastNotification(toastXml);  
  36.   
  37.             ToastNotificationManager.CreateToastNotifier().Show(toast);  
  38.         }  
  39.     }  
  40. }   
Step 7

Click 'F5' or "Build" to "Run" your application. Running this project, you will have a result like below.
 
Xamarin.Android
 
 
 
Xamarin.UWP 
 
 
 
Finally, we have successfully created a Xamarin.Forms ToastMessage application.

Please download the source code here.


Similar Articles