Search code examples
xamarinxamarin.formsxamarin.androidprism

Xamarin Prism : Dependency Service Toast Message


I want to implement a Toast message on my Android app. So I created in my shared code the interface :

  namespace TravelApp.Renderers
{
    public interface IToast
    {
        void show(string message);
    }
}

Then I created on my Android project the interface implementation

  [assembly:Dependency(typeof(TravelApp.Droid.Toast))]
  namespace TravelApp.Droid
{
    public class Toast : IToast
    {
        public void show(string message)
        {
            Android.Widget.Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
        }
    }
}

In my XAML file I used a pancakeview, when I tap on this view I want to display my toast Message :

<pancake:PancakeView x:Name="MyPancakecs" HorizontalOptions="EndAndExpand" 
                                         VerticalOptions="EndAndExpand" 
                                         CornerRadius="60" 
                                         HeightRequest="50"
                                         WidthRequest="50"
                                     BackgroundColor="{StaticResource BackgroundColor}" 
                                     Margin="0,0,60,0" 
                                     Padding="15"
                                      >
                        <Image Source="TrayPlus"></Image>
                        <pancake:PancakeView.GestureRecognizers>
                               <TapGestureRecognizer Command="{Binding ToastMyToaster}"/>

                        </pancake:PancakeView.GestureRecognizers>
                        </pancake:PancakeView>

Then I register my container in a PlateformInitializer class in my android Project :

namespace TravelApp.Droid
{
    public class PlatformInitializer : IPlatformInitializer
    {
        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IToast,Toast>();
        }
    }
}

I added it in my App constructor in MainActivity.cs :

LoadApplication(new App(new PlatformInitializer())) ;

And then in my ViewModel I add a IToast object in my constructor:

namespace TravelApp.ViewModels
    {
        public class TravelListViewModel : BindableBase
        {
            private string _messageToast;
            public string MessageToast
            {
                get { return _messageToast; }
                set { SetProperty(ref _messageToast, value); }
            }
            public DelegateCommand ToastMyToaster;

            public TravelListViewModel(INavigationService navigationService, ITravelRepository travelRepository, IToast Toaster)
            {

                this._navigationService = navigationService;
                this._travelRepository = travelRepository;
                this._messageToast = "Test Toaster";
                this._toaster = Toaster;
                this.ToastMyToaster = new DelegateCommand(ToastShow);

            }
            private void ToastShow()
            {
                this._toaster.show(MessageToast);
            }
        }

In my research I used this documentation : https://prismlibrary.com/docs/xamarin-forms/Dependency-Service.html

However when I run the code and tap on my pancakeview, there is no message displayed, I'm not even sure that the command is triggered...

I don't know if I needed to implement the IPlateformInitializer.

Thank you for your help,


Solution

  • Here is how I did it.

    Shared Project

    public interface IToast
        {
            void LongAlert(string message);
            void ShortAlert(string message);
        }
    

    Android Project (Renderer) You need to install CurrentActivityPlugin

    [assembly: Dependency(typeof(AndroidToast))]
    namespace yournamespace
    {
        public class AndroidToast : IToast
        {
            public void LongAlert(string message)
            {
                Toast.MakeText(CrossCurrentActivity.Current.Activity, message, ToastLength.Long).Show();
            }
            public void ShortAlert(string message)
            {
                Toast.MakeText(CrossCurrentActivity.Current.Activity, message, ToastLength.Short).Show();
            }
        }
    }
    

    Calling toast in my shared project

    internal static void Toast(string message, bool isShort=false)
            {
                var toast = DependencyService.Get<IToast>();
                if (toast != null)
                {
                    if (!isShort)
                        toast.LongAlert(message);
                    else
                        toast.ShortAlert(message);
                }
            }
    

    Somewhere in my viewModel / any where in Shared project

    Helper.Toast("message here");