Tuesday, June 16, 2020

Toast in Xamarin Forms


This blog, we are going to see how to implement Toast Message in Xamarin Forms for Android and iOS. This project, we can use dependency injection to display toast and not using any third-party plugin. The android has a default widget for toast but iOS has an only alert controller. 


Let’s start the story 

Step 1: 

Create Xamarin Forms Mobile App in Visual Studio for Mac. For that, go to Visual Studio for Mac >> New >> In the left plane select Cross-Platform and center plane select Blank Xamarin Forms App and click Next >> Give Application Name and Target Platforms, click Next and again click Create. 

Xamarin Forms

Step 2: 

After project creation, expand the Shared project and create an IMessage.cs interface under Interface Folder. For that, right-click the shared project and select new File >> In the dialog window, select interface and give name as IMessage and click Add. Create two methods for a long and short message, the code is given below. 


Platform-Specific Configuration 

Android Project 

Now, Expand the Android project and create MessageAndroid class. This MessageAndroid class inherits from the IMessage interface, that we already created in Shared Project and register this class as a dependency. This Code is given below. 


iOS Project 

Next, open iOS Project and create MessageiOS class and as well as inherit the same IMessage interface to this class and the full source code given below. Here we created a simple alert Controller and timer Scheduled to disappear the alert controller.  


Step 3: 

Now, design your user interface in MainPage.xaml file in Shared Project. For that, go to Solution Explorer >> Shared Project >> double click and open MainPage.xaml and design two-button with the clicked event. The code is given below. 


Next, open MainPage.cs file and call dependency service to show toast and the code is given below 


Step 4: 

Run, your application, and click the buttons to show a toast message. The screenshot is given below.  


Toast in Xamarin Form

 The Full Source Code in Github


I hope you, this article helpful for you, and if you have any suggestions or comments post in the comment below. Thanks for reading. 

1 comment

You're comment here