Building a simple message popup control for Xamarin.Forms

quizgif.gifA simple solution

I needed a quick way to dynamically display a centered, overlaid message in the quiz app I’m working on for my daughter’s elementary school.

This is just a message for status changes and not meant to be interactable, but it’s usually fired in C# from a ViewModel class or UI click handler because I don’t really care what page I’m on when it’s displayed.

It looks like this (the “Quiz Questions updated” block).

AbsoluteLayout is the secret sauce

I already had most of my layouts built (in XAML), and they had StackLayout roots rather than AbsoluteLayouts. I didn’t want to rebuild them in C# in order to make them inherit an AbsoluteLayout – a great suggestion by Brandon Minnick (@BrandonXamarin), but I’m too late in the process for all that refactoring.

An okay, but not perfect, compromise is this snippet:

public static class Popper
{
	public async static Task Pop (string message, AbsoluteLayout attachLayout, int showforMilliseconds = 1500)
	{
		var container = new StackLayout
		{
			HorizontalOptions = LayoutOptions.Center,
			VerticalOptions = LayoutOptions.Center,
			BackgroundColor = Color.FromHex ("#DDEFEFEF"),
			Padding = 10
		};

		var label = new Label
		{
			Text = message,
			FontAttributes = FontAttributes.Bold,
			Style = (Style)Application.Current.Resources["PopupText"]
		};

		container.Children.Add (label);

		container.Scale = 0;
		container.Opacity = 0;

		attachLayout.Children.Add (container, attachLayout.Bounds, AbsoluteLayoutFlags.PositionProportional);
		container.ScaleTo (1.0f, 100);
		container.FadeTo (1.0f, 100);

		await Task.Delay (showforMilliseconds);

		container.ScaleTo (0.0f, 250);
		await container.FadeTo (0.0f, 250);
		attachLayout.Children.Remove (container);
	}
}

What I like about this approach is that I can fire it from anywhere and attach it to any AbsoluteLayout. The message will be added to the absolute layout in the middle, animated, and then removed from the absolute layout.

What I don’t like about it is that I wish this was on my BasePage. The method makes an assumption that there is an AbsoluteLayout root to attach to.

Until I figure out another way of sharing that AbsoluteLayout, this simple solution gets me exactly what I need. Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s