Learn the Code to Display a Toast Message in Xamarin.Forms

hqdefault

As we already know that Xamarin is a trendiest cross-platform app development technology, which is well supported by the Microsoft and allows a developer to build a bug-less native mobile application in the shortest time limit by granting to reuse the similar code in the other app development. Due to the several advanced and classy features along with multi-platform nature, Xamarin becomes the most preferred choice of developers.

What is Toasts message?

It is the kind of a message that gets disappear in a few seconds from the mobile screen and allows a user to use the application without getting stuck anywhere in it.

How to add a Toast in Xamarin.Forms?

Firstly, create a new project and an interface in it namely “IToastMessage”. Now create a function in that file and pass the string parameters in it as:

Public interface IToastMessage

{ void DisplayMessage(string message) ; }

Code for Xamarin Android:

using Android.Widget;
using YourApp.Droid;
using Xamarin.Forms;
[assembly:Dependency(typeof(Message_Droid))]
Namespace YourApp.Droid
{
public class Message_Droid:Itoast
{
public  void DisplayMessage(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
}
}
}

Code for Xamarin iOS

At first, create a class in your file as “message_iOS.cs” and use the code as below;

Using Xamarin.Forms;
Using YourApp.iOS;
[assembly:Dependency(typeof(Message_iOS))]
Namespace YourApp.iOS
{
Public cass Message_iOS:IToastMessage
{
Const double LONG_DELAY=2.5;
Const double SHORT_DELAY=1.5;
NSTimer alertDelay;
UIAlertController alert:
Public void DisplayMessage(srting message)
{
ShowAlert(message, Short_Delay);
}
Void ShowAlert(srting message, double seconds)
{
alertDelay=NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
Dismissmessage();
}
Alert=UIAlertController.Create(null, message, UIAlertControllerSytle.Alert);
UIApplication.ShareApplication.Keywindow.RootViewController.PresentViewController(alert,true,null);
}
Void dismissMessage()
{
If (alert != null)
{
Alert.DisMissViewController(true, null);
}
If (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
}
Now in the final step, write the code in your main file;
Files:DependencyService.Get<IToastMessage>().DisplayMessage(“Your message is here”);
Its all done for to add a Toast Message in your Xamarin.Forms.

by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>