Search code examples
xamarinxamarin.formstoastsnackbar

How to display a snackbar or toast at top of the screen in xamarin forms


I implemented snackbar in xamarin project. But I need to displaty that snackbar at top of the screen.

Code:

SnackBarOptions options = new SnackBarOptions
{
    MessageOptions = new MessageOptions
    {
        Foreground = Color.Black,
        Message = toastMsg,
        Padding= 15
        
    },
    BackgroundColor = Color.White,
    Duration = TimeSpan.FromSeconds(8),
    CornerRadius = 15,
    IsRtl = true,
    
    
};
Application.Current.MainPage.DisplaySnackBarAsync(options);

Solution

  • You need to write custom platform specific code to achieve this:

    Android:

    
        GradientDrawable shape = new GradientDrawable();
        shape.SetCornerRadius(15); //For Corner radius
        shape.SetColor(Android.Graphics.Color.Black);
        var contentView = Xamarin.Essentials.Platform.CurrentActivity?.FindViewById(Android.Resource.Id.Content);
        Snackbar snackBar = Snackbar.Make(contentView, "Your Message", 5000);
        Android.Views.View view = snackBar.View;
        view.SetBackground(shape);
        FrameLayout.LayoutParams frameLayout = (FrameLayout.LayoutParams)view.LayoutParameters;
        frameLayout.Gravity = GravityFlags.Top;
        view.LayoutParameters = frameLayout;
        snackBar.Show();