Category Archives: Awesome

Let’s draw basic 2D Shapes with SkiaSharp…

So on my last post I shared a recap of my tech talk on SkiaSharp with Xamarin.Forms, check it out if you missed it: So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

There I talked about some of the most important parts of the whole 1 hour plus presentation-hands-on-labs session, in which I didn’t share all the details of the whole session. I did a pretty comprehensive demo session there, specially about the 2D drawing basics of SkiaSharp, which I didn’t highlight in that post.

Basic 2D Shapes with SkiaSharp…

So today I thought of sharing the demos I did there, about basic 2D shapes drawing with SkiaSharp more extensively… 🙂 Since there seem to be a lack of tutorials explaining this topic of, “draw basic Shapes with SkiaSharp”, which I think should be more important for beginners!

So buckle up fellas, let’s see how we could draw some of the most commonly used 2D shapes with SkiaSharp with ease… 😉

There’s many out of the box support for drawing basic 2D Shapes from SkiaSharp, such as DrawCircle(), DrawRectangle(), DrawLine(), DrawOval() and so on many more.  You could stright away use those methods or you could even go around it and use Paths and Lines drawing methods of SkiaSharp in order to draw them, which is completely up to you.

But SkiaSharp doesn’t have methods for drawing for every single kind of Geometrical shape there is out there. So if you want to draw some kind of complex shape, then you could basically use a combination of Paths and Lines drawing methods in SkiaSharp, which has many kinds of methods you could come up with. 😉 that’s the beauty of SkiaSharp! Anyways the choice of drawing methods are totally up to you!

Now if you want to get ahead of yourself, you may grab the live hands on demo code I did at the presentation which includes all of the below code, right from my github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo

Just on a note, here I will not be discussing basics of SkiaSharp or the setting up of SkiaSharp library or the Canvas properties and behaviours, I’ll directly get into the programming of the shapes drawing, but if you want to get a head start, head off to Xamarin SkiaSharp Documentation or my previous post, So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

1. Simple Stroke Line…

private void SkCanvasView_OnPaintSurface
		(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	// Drawing Stroke
	using (SKPaint skPaint = new SKPaint())
	{
		skPaint.Style = SKPaintStyle.Stroke;
		skPaint.IsAntialias = true;
		skPaint.Color = SKColors.Red;
		skPaint.StrokeWidth = 10;
		skPaint.StrokeCap = SKStrokeCap.Round;

		skCanvas.DrawLine(-50, -50, 50, 50, skPaint);
	}
}

 

We use the DrawLine() and pass in the Line’s starting point’s XY position and and ending point’s XY position, while passing in the paint configuration, SKPaint as we wish.

 

Since SkiaSharp support pure Xamarin.Forms you can straight away run all your native projects without any hassle of handling native code.

2. Drawing a Circle (Filled)

// Drawing a Circle
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Blue;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}

 

We shall be using the DrawCircle() whilst passing in the Circle’s center XY position and desired radius for it. To define whether its a Filled or Non-Filled circle we’ll be using Style property in our SKPaint configuration.

 

Next let’s draw a Circle with just the stroke (with filling the inner of the circle).

3. Drawing a Circle (Un-filled)

We do this by setting the Style property to Stroke! and everything else is the same 🙂

// Drawing a Circle Stroke
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Stroke;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Red;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}

 

 

Look how simple eh 😉

4. A Square Rectangle!

How about a standard Rectangle? We shall use the SKRect object to configure our Rectangle as we wish and draw it up!

// Draw Rectangle
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.DeepPink,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(100, 100);
skRectangle.Location = new SKPoint(-100f / 2, -100f / 2);

skCanvas.DrawRect(skRectangle, skPaint);

 

See it in action? 😉

 

The square root of 69 is 8 something, right? – Drake 😉 lol

5. Let’s draw an Ellipse…

There’s many ways to draw an Eclipse, but most common way is to use DrawOval(), as well as other kinds of complex drawings.

// Draw Ellipse
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.OrangeRed,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(150, 100);
skRectangle.Location = new SKPoint(-100f / 2, -100f / 2);

skCanvas.DrawOval(skRectangle, skPaint);

 

 

So here we’re configuring a Rectangle with SKRect, which an Ellipse could be mathematically consist of.

6. How about an Arc shape?

Well it’s basically the same concept as of an Ellipse, but since we need an “Arc”, we’re going to use some basic mathematical angles to configure the starting angle, startAngle and sweep angle, sweepAngle of the Arc we’re going to draw with a Path object.

// Draw Arc
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.BlueViolet,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(150, 150);
skRectangle.Location = new SKPoint(-150f / 2, -150f / 2);

float startAngle = -90;
float sweepAngle = 230; // (75 / 100) * 360

SKPath skPath = new SKPath();
skPath.AddArc(skRectangle, startAngle, sweepAngle);

skCanvas.DrawPath(skPath, skPaint);

 

So there we’re configuring our Path object to start off from -90 degrees and ends up at 230 degrees from the start point, drawing the Arc shape. Notice the comment I’ve added there, showcasing how you could also calculate the Arc’s drawing angle as a percentage value. 😀

 

Pretty cool eh! 😉

7. Did we forget Text?

Did you know you could even draw text on a SkiaSharp canvas right away by using DrawText() method.

// Drawing Text
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.DarkSlateBlue;
	skPaint.TextAlign = SKTextAlign.Center;
	skPaint.TextSize = 20;

	skCanvas.DrawText("Hello World!", 0, 0, skPaint);
}

 

SkPaint object holds several properties for drawing Text on the canvas, such as TextAlright, TextSize and many more you could play around with..

 

Hello World, indeed! 😉

8. Let’ draw a simple Triangle?

Well SkiaSharp doesn’t have a out of the box method call for drawing a Triangle, this is where simple Drawing path and points comes into play.

So basically what we do is, we’ll draw three lines that’s interconnects at the ending points, using DrawPoints() method and pass in the list of Points that’ll draw the Lines…

// Draw Rectangle
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.DeepSkyBlue,
	StrokeWidth = 10,
	IsAntialias = true,
	StrokeCap = SKStrokeCap.Round
};

SKPoint[] skPointsList = new SKPoint[]
{
	// Path 1
	new SKPoint(+50,0),
	new SKPoint(0,-70),

	// path 2
	new SKPoint(0,-70),
	new SKPoint(-50,0),

	// path 3
	new SKPoint(-50,0),
	new SKPoint(+50,0),
};

skCanvas.DrawPoints(SKPointMode.Lines, skPointsList, skPaint);

 

See it first may be?

 

So now if you think about it, you could actually draw any kind of a Shape with interconnecting Points and Paths using the above method. 😀

9. Draw any Shape?

It’s true earlier step, in Triangle drawing I said you could use the DrawPoints() and a bunch of Points to draw any kind of shape in SkiaSharp. This is actually a painful, but there’s actually a better way… 😉 yaay!

So basically if you needed to draw any kind of shape, all you need is a Path and a bunch of Points that interconnects. A much easier way to do this is by using a SKPath configuration object, using this you could pass define the Starting Point of the drawing path, move around the drawing path with interconnecting Points by using MoveTo() and LineTo() calls. For this you use the mighty DrawPath() method, which you could use to draw anything on the canvas. 😀

// Draw any kind of Shape
SKPaint strokePaint = new SKPaint
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.Black,
	StrokeWidth = 10,
	IsAntialias = true,
};

// Create the path
SKPath path = new SKPath();

// Define the drawing path points
path.MoveTo(+50, 0); // start point
path.LineTo(+50, -50); // first move to this point
path.LineTo(-30, -80); // move to this point
path.LineTo(-70, 0); // then move to this point
path.LineTo(-10, +90); // then move to this point
path.LineTo(+50, 0); // end point

path.Close(); // make sure path is closed
// draw the path with paint object
skCanvas.DrawPath(path, strokePaint);

 

There you go…

 

So with the use of SKPath, you could draw any kind of 2D shape as you wish… 😀

10. Final shape?

Oh sorry! there ain’t none! 😛 just put up a 10th point for the fun of it! 😉

Well you could grab all of the above code up in my Github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo That right there is actually the live hands on demo code I did at my original presentation…

So now get out of here and start drawing 2D with SkiaSharp! 😀

or may be check out my talk on SkiaSharp…

Shape the love fellas! 😀

-Udara Alwis.

Advertisements

An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! ;)

Imagine you wanted to prompt your user with a popup alert dialog (which is also transparent, because its cool! lol) 😉 asking them to enter some value and you want to await the whole task (make it awaitable) while you’re at it, so the execution will halt until the user enter the value, and then retrieve the user entered value to the point of origin? 😀

And just to add some sugar to it, may be you wanted to customize and decorate the appearance of the input view?

Something like this?

Seems pretty cool yeah! That’s what I’m gonna share today!

Right outta Xamarin.Forms?

Now there’s no way you could do either of those things in that scenario right out of Xamarin.Forms! Nope, not with a Modal Popup, which doesn’t support transparency, and not even with DisplayAlerts or ActionSheets, since the’re not customizable, they don’t allow text input or any kind of custom input view, only multiple button selections.

So how could I do it?

Let me explain fellas!

So for transparency and ultimate flexibility of setting up custom popup views, we are going to use the awesome Rg.Plugins.Popup library for Xamarin.Forms and to make the whole Task awaitable let’s use a TaskCompletionSource (Thank you dot net)! 😉

So the trick here for adding custom input views to the popup page, is by creating our Xamarin.Forms custom views using a ContentView and set them to the Content of popup page.

Alright then time for some coding!

Let the coding begin…

But first, setting up!

First thing first create a Xamarin.Forms PCL project in Visual Studio. 🙂

Then install Rg.Plugins.Popup library for Xamarin.Forms through Nuget Package manager.

I’ve actually written a blog post about Rg.Plugins.Popup in my blog right here: So I created a Popup with Transparent background in Xamarin Forms… 😉

Create the Transparent Popup Page…

Once you’re done with that, let’s create our custom Transparent Popup Page using the Rg.Plugins.Popup we just installed.

Something to keep in mind,

  • We should allow it to use Generic data types as for the return data type. 😀
  • Popup page provides us with many cool features, including Page background click handling and back button press handling, which we will override as of disable page background click to dismissal and disable back button press cancellation.
  • Pass in a View and set it to the PopupPage’s Content property, which we will attach the custom input view we want to use in our popup page.
  • Set the transparency level to 0.4 of alpha value.

Let’s call it InputAlertDialogBase.

/// <summary>
/// The awesome Transparent Popup Page
/// sub-classed from Rg.Plugins.Popup
/// Customized for our usecase with
/// Generic data type support for the result
/// </summary>
/// <typeparam name="T"></typeparam>
public class InputAlertDialogBase<T> : PopupPage
{
	public InputAlertDialogBase(View contentBody)
	{
		Content = contentBody;

		this.BackgroundColor = new Color(0, 0, 0, 0.4);
	}

	// Method for animation child in PopupPage
	// Invoced after custom animation end
	protected override Task OnAppearingAnimationEnd()
	{
		return Content.FadeTo(1);
	}

	// Method for animation child in PopupPage
	// Invoked before custom animation begin
	protected override Task OnDisappearingAnimationBegin()
	{
		return Content.FadeTo(1);
	}

	protected override bool OnBackButtonPressed()
	{
		// Prevent back button pressed action on android
		//return base.OnBackButtonPressed();
		return true;
	}

	// Invoced when background is clicked
	protected override bool OnBackgroundClicked()
	{
		// Prevent background clicked action
		//return base.OnBackgroundClicked();
		return false;
	}
}

 

There you go, over to the next step!

Configure the await-able Task properties…

So let’s create a Task and TaskCompletionSource inside our InputAlertDialogBase, to handle await-ability of our “Transparent, Custom, Popup Input Dialog” as I’ve mentioned in the blog title! 😉

public class InputAlertDialogBase<T> : PopupPage
{
	// the awaitable task
	public Task<T> PageClosedTask { get { return PageClosedTaskCompletionSource.Task; } }

	// the task completion source
	public TaskCompletionSource<T> PageClosedTaskCompletionSource { get; set; }

	public InputAlertDialogBase(View contentBody)
	{
		...

		// init the task completion source
		PageClosedTaskCompletionSource = new System.Threading.Tasks.TaskCompletionSource<T>();

		...
	}

	...
}

 

Note that how we are initializing the TaskCompletionSource in the Constructor.

Alright, now our Transparent Popup is ready. Next we need to construct the Custom Input View, that we are going to pass into the InputAlertDialogBase to display and retrieve data input (text or any kind) from the User. 😀

Create your Custom Input View! 😀

Alright this step is totally up to your desires, you could construct any kind of a Custom Input View to be displayed on top of the InputAlertDialogBase we just created above, and retrieve the User’s inputs.

So for this example, let’s create a simple View with Title Label, Text Entry and Ok button yeah! 😉 Also let’s add a simple validation Label inside it to show up if the User tries to leave the Text Entry empty and hit the ok button to quit.

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    x:Class="XFCustomInputAlertDialog.InputViews.TextInputView"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentView.Content>
        <StackLayout
            Padding="10"
            BackgroundColor="White"
            HorizontalOptions="CenterAndExpand"
            Spacing="5"
            VerticalOptions="CenterAndExpand">
            <Label
                x:Name="TitleLabel"
                FontSize="Medium"
                Text="Enter the value:" />
            <Label
                x:Name="ValidationLabel"
                FontSize="Micro"
                IsVisible="False"
                Text="You can't leave this field empty!"
                TextColor="Red" />
            <Entry x:Name="InputEntry" Placeholder="Enter Here..." />
            <Button x:Name="CloseButton" Text="Ok">
                <Button.HeightRequest>
                    <OnPlatform x:TypeArguments="x:Double">
                        <On Platform="Android" Value="40" />
                        <On Platform="iOS" Value="30" />
                    </OnPlatform>
                </Button.HeightRequest>
            </Button>
        </StackLayout>
    </ContentView.Content>
</ContentView>

 

As you can see we have created a simple ContentView with a custom Text input view! 😀

Notice that we have explicitly named all the elements and added a button click event, this is to make it easy to set custom textual values to the elements and to handle the OK button’s click event as for the closing of the Popup Page. 🙂

Pretty simple yeah, next let’s handle the back end of this custom View to manage the Textual values, Ok button’s click event and validations.

Let’s manage code-behind of Custom Input View…

Now this is important, if you consider a ContentView, all it’s Child elements are private to it’s class scope, so we can’t observe or interact with any of the property value changes or behaviors from outside of the View.

Therefore we need to create custom properties that will expose those required values and events to the public.

Something to keep in mind here,

  • In order to customize the values displayed in the Child elements of the ContentView (Label,Button, etc..) we should pass in the values to the Constructor and set them to the Child elements there.
  • We should create a public EventHandler to handle the Ok Button’s click event from outside the View and add a public string Propery to expose the text Entry’s value to the public.
  • Subscribe to the Entry’s TextChanged event to reflect the value the public string property.
  • Create a public bindable Boolean property to display or hide Validation label in the ContentView. Or you could handle this internally in the View on the Ok Button’s click event as well, but it would be nice if we could expose the Validations to public so we could handle it outside the View.

public partial class TextInputView : ContentView
{
	// public event handler to expose 
	// the Ok button's click event
	public EventHandler CloseButtonEventHandler { get; set; }

	// public string to expose the 
	// text Entry input's value
	public string TextInputResult { get; set; }

	public TextInputView(string titleText, 
          string placeHolderText, string closeButtonText, 
           string validationLabelText)
	{
		InitializeComponent();

		// update the Element's textual values
		TitleLabel.Text = titleText;
		InputEntry.Placeholder = placeHolderText;
		CloseButton.Text = closeButtonText;
		ValidationLabel.Text = validationLabelText;

		// handling events to expose to public
		CloseButton.Clicked += CloseButton_Clicked;
		InputEntry.TextChanged += InputEntry_TextChanged;
	}

	private void CloseButton_Clicked(object sender, EventArgs e)
	{
		// invoke the event handler if its being subscribed
		CloseButtonEventHandler?.Invoke(this, e);
	}

	private void InputEntry_TextChanged(object sender,
					TextChangedEventArgs e)
	{
		// update the public string value 
		// accordingly to the text Entry's value
		TextInputResult = InputEntry.Text;
	}
}

 

So you can see we are passing in all the required values to set to our Child element’s we are passing in to the Constructor and setting them up there. Also we are subscribing to the Ok Button’s OnClick event and text Entry’s TextChanged event.

Inside the CloseButton_Clicked() event we are invoking the public EventHandler CloseButtonEventHandler if it’s being subscribed to by outside.

As well as  the Entry’s InputEntry_TextChanged() event we are updating the public TextInputResult to reflect the Entry’s text value to the public.

Don’t forget to handle Validations…

Oh and here’s the Bindable Boolean property you should include inside the TextInputView code behind to handle the Validations from outside the View.

public partial class TextInputView : ContentView
{
	...
	
	public static readonly BindableProperty 
           IsValidationLabelVisibleProperty =
		BindableProperty.Create(
			nameof(IsValidationLabelVisible),
			typeof(bool),
			typeof(TextInputView),
			false, BindingMode.OneWay, null,
			(bindable, value, newValue) =>
			{
				if ((bool)newValue)
				{
					  
		((TextInputView)bindable).ValidationLabel
					 .IsVisible = true;
				}
				else
				{
					 
		((TextInputView)bindable).ValidationLabel
					.IsVisible = false;
				}
			});

	/// <summary>
	/// Gets or Sets if the ValidationLabel is visible
	/// </summary>
	public bool IsValidationLabelVisible
	{
		get
		{
			return (bool)GetValue(
                             IsValidationLabelVisibleProperty);
		}
		set
		{
			SetValue(
                         IsValidationLabelVisibleProperty, value);
		}
	}
	
	...
}

 

Now speaking of the bindable IsValidationLabelVisibleProperty, we are updating the Validation Label’s visibility based on its value changes accordingly. 🙂

Following this method, you can create any kind of custom Input Views to be attached to our Transparent Popup Page. 🙂 All you need to do is expose the required Values and Events to the public.

Alright next step…

Time to assemble everything and consume it!

Now we are going to put everything together and get it to be used as our “awaitable Transparent, Custom, Popup Input Dialog”! 😉

Somethings to keep in mind here,

  • We need to initialize our TextInputView by passing in the parameters we would like the necessary child elements to display
  • Create an InputAlertDialogBase<string>(), yes of type string, since we are going to return a string from the Popup Alert.
  •  Subscribe to the CloseButtonEventHandler of TextInputView’s instance to handle validation and reflect the Text input value to the TaskCompletionSource.
  • Push the popup page instance to Navigation Stack and await the page’s Task
  • Upon result retrieval Pop the page from Stack and return the user inserted value.

Alright let’s do it…

private async Task<string> LaunchTextInputPopup()
{
	// create the TextInputView
	var inputView = new TextInputView(
		"What's your name?", "enter here...", 
		"Ok", "Ops! Can't leave this empty!");

	// create the Transparent Popup Page
	// of type string since we need a string return
	var popup = new InputAlertDialogBase<string>(inputView);

	// subscribe to the TextInputView's Button click event
	inputView.CloseButtonEventHandler +=
		(sender, obj) =>
		{
			if (!string.IsNullOrEmpty(
                         ((TextInputView)sender).TextInputResult))
			{
				
                            ((TextInputView)sender)
                               .IsValidationLabelVisible = false;
				
                            // update the page completion source
                            popup.PageClosedTaskCompletionSource
                                .SetResult(
                                ((TextInputView)sender)
                                      .TextInputResult);
			}
			else
			{
				
                             ((TextInputView)sender)
                                 .IsValidationLabelVisible = true;
			}
		};

	// Push the page to Navigation Stack
	await PopupNavigation.PushAsync(popup);

	// await for the user to enter the text input
	var result = await popup.PageClosedTask;

	// Pop the page from Navigation Stack
	await PopupNavigation.PopAsync();

	// return user inserted text value
	return result;
}

 

There you go, step by step as I explained before you can see how it’s being consumed. Specially inside the CloseButtonEventHandler, every time the event fires we are checking the TextInputResult property and enabling or disabling the IsValidationLabelVisible property, as well as updating the PageClosedTaskCompletionSource property value if a text value is being entered by the User, which will in return update the awaiting PageClosedTask and task will proceed to completion state, then return the value after popping the Page. 😀

There you go! 😀 How straight forward is that! 😉

Keep in mind like I said before you can add any kind of a customized View on top of our Transparent Popup Page, and retrieve any kind of result as you expect from the User following the same steps. 😀

Let’s see this in action…

 

Look at that coolness right! 😉

Since it’s full on Xamarin.Forms, and doesn’t have a single line of native code, you could straight up run this implementation on all Android, iOS, UWP, WinPhone as you wish! 😀

I want more! 😮

Alright now that’s just a little bit of basic head start of what you could do, whereas if you get creative and smart you could do a lot more cool stuff like this…

  

 

 

There you have it, some cool stuff I played around with my implementation. 😉

You can grab the Github code from here: github.com/UdaraAlwis/XFCustomInputAlertDialog

Well fellas, that’s it for now!

Enjoy! 😀 Share the love!

-Udara Alwis 😀

Yaay! I became a Xamarin Certified Mobile Developer! :D

So finally on 9th of June 2017, I became a Xamarin Certified Mobile Developer. So here’s my experience of the whole Xamarin University, Certification Exam, and some tips and tricks that might help you! 🙂

Well I’ve been using Xamarin Platform for over 2 and half years now, but I never really thought of getting the official Xamarin Certification until recently my boss encouraged me to and financially supported it.

Down the memory lane of my Mobile Development enthusiasm…

So here’s a little sharing of memories down the memory lane and some tips for getting the Xamarin Certification.

I first started off developing mobile apps on Android platform, given my love for Java programming back in the early days. So I self learned Android App Development back in the middle of 1st year of my college using online tutorials and documentation.

Then at the end of 1st year, I was introduced to Windows Phone App development, which I got completely hooked on it, and then Windows Store App Development and so on, where I ended up publishing over 20+ apps to the Microsoft App Store during the next few years.

Next lucky enough I got a mobile developer opportunity at a medium size local company where it was for Xamarin Mobile Development back in 2014 December. 😀

Learning the whole Xamarin Platform by myself, I ended up completing a full fledged mobile app for that project in that company using Xamarin Forms.

Finally in 2015 December, got an overseas opportunity in Singapore for a Xamarin Mobile Developer position, which is where I ended up mastering the Xamarin Platform, Xamarin Android/iOS native development, hacking to push boundaries of the platform and so on and finally living my dream of being a Mobile App Developer. 😀

And that is where I’m currently working at June 2017, enjoying everyday of it while diving in the goodness of Xamarin Mobile Development. 😉


Xamarin University Training and Certification Preparation…

I was lucky enough my company sponsored me for Xamarin University Subscription. Otherwise its about 1000 USD for 1 year subscription or there a new monthly subscription plan with a very reasonable pricing.

Once you have the subscription you get full access for all the incredible learning materials and live lecture sessions in Xamarin University.

Is it worth it?

Now although at this point I already had like 2 years of Xamarin Mobile developement experience, I must admit that I learned way more and strengthened my knowledge on Xamarin top to bottom thanks to Xamarin University. So if you ask me if it’s worth it? at least for the Knowledge? DEFINITELY YES!

Mandatory Sessions

There’s a mandatory list of sessions that you have to complete before taking the exam, you could completely them either by attending the live lecture sessions or taking self-learn sessions (if available). Yes, some of those mandatory sessions doesn’t have the ‘self-learn’ option yet, so you have to attend to a live lecture session and get your attendance marked for it. 🙂

Instructors?

Mark my words, the instructors in Xamarin University are top-notch, and industry experts with a lot of knowledge and experience, there’s no doubt about them. You can ask anything from them regarding the session, even while the session is going on, they are very helpful and friendly, not to mention their great teaching skills. 🙂

Memorizing vs Understanding!

Do not MEMORIZE! just UNDERSTAND the content! The sessions are structured in a way that it helps you to actually understand the content with step by step exercises. I’ve never taken a single note on any of the sessions, nor tried to memorize stuff(although I’m not very good at it either), just followed through sessions and focused well during them. That’s all it takes!

Anything else?

You can take any live lecture session as many times as you wish, until you feel comfortable with the topic. There’s also many extra sessions you could attend to improve your knowledge in Azure, UI Test, Xamarin Android, Xamarin iOS. It’s good to keep in mind that the exam mandatory sessions are mainly about Xamarin Forms cross platform related topics, so you don’t have to worry if you don’t have much in-depth knowledge about native mobile development. 🙂

They also provide you a Study-Guide check-list to go through to make sure you’re prepared for what’s actually required: https://university.xamarin.com/content/certification#study-guide

Once you’ve completed the mandatory sessions, then you become eligible to sit for the certification exam!


Certification Examination!

So the Certificate Exam is a 3 hours, MCQ exam (Multiple Choice Question) which has 150 questions, and you should score over 80% in order to pass the exam.

The questions scope…

The questions are going to be completely based on the mandatory sessions in Xamarin University. Heavily focused on the Xamarin.Forms cross platform related topics. Personally I did not get any questions that are out of the scope.

So how were the questions…

If you’ve got a solid knowledge on the mandatory sessions, then you have nothing to worry about. Not keep this in mind, about 40% of the questions are straight and easy, but the rest are not going to be hard, but tricky, meaning it’s going to be little bit twisted, so you need to pay good attention to the details in each question before you pick the answer. 😉

Understand the content in the sessions, not memorize!

Basically you won’t be able to make it through the exam if you’re just trying to ‘memorize’ everything in your head, you need to have a ‘good understanding’ of the session content, in order to answer the tricky 60% of the questions.

After the exam?

Once you finish the exam, you get the results immediately. 😉 Then its time to PARRTTAAYYY!!! 😀

Xamarin University and Certification benefits!

First of all the incredible amount of knowledge and experience you gain in the whole process of Xamairn University and the Certification is priceless.

Not to mention the global recognition as Xamarin Certified Mobile Developer, having the official certificate directly validates you as someone who actually knows your way around Xamarin-stuff. Although it does not prove you as an ‘expert’, which is totally dependent on your personal industry experience.

Access to Xamarin DevConnect portal, to showcase your portfolio and connect with fellow developers.

There are few other awesome benefits you get according to Xamarin official site as follows. Certification is valid for 1 year from the date you have passed the exam. Certifications can be verified on our public Xamarin Certified Developers page.

Receive a badge, fun Xamarin swag, and an invitation to join the official Xamarin Certified Developers community on LinkedIn.

Cool, so what do I get to show off?

Except for the massive amount of knowledge and experience I gained from the Xamarin University Sessions and Training, here are some other show-off stuff I got after being certified.

So brace yourselves for some self promotional bragging! 😛

Xamarin Certified Developer Verification Online:

https://university.xamarin.com/certification?q=Udara@xamariners.com#verify

You get a link that can be shared online for the verification of your Certification status. This is the source you could include in your LinkedIn or personal portfolio for the verification.

Xamarin University Profile Badge: 

Once you get the certification, your Xamarin University profile gets updated as such.

Xamarin Certified Developer Certification (soft copy): 

You actually get a PDF version of your certification (here is a screenshot of it).

Bunch of Xamarin Certified Developer badge Images (HD):

Then you get a whole bunch of Certified Mobile Developer badges in low, mid and high resolution for you to share on any of your websites or portfolios. 🙂

Xamarin DevConnect Profile:

You get access to Xamarin DevConnect, the official Xamarin Certified Developer portal from Xamarin, where you can publish your portfolio, connect with fellow certified developers from all over the world, and open up yourself for new opportunities.

https://devconnect.xamarin.com/profile/389


Well that’s it all I got for now… 😀

Although some claim that you get kind of a Xamarin souvenir trophy and a goodie bag by mail, but I’m yet to get any of that. lol. *fingers cross* 😛

So If anyone needs any help or clarifications regarding Xamarin Certification, I’m more than happy to help, drop me a mail or comment down in the post. 🙂

To get started:  https://www.xamarin.com/university

Good luck everyone with your Xamarin Certification! 🙂

Cheers!

The three awesome tools by Xamarin! Workbooks|Profiler|Inspector

Last Friday (20th January, 2017) I did a tech talk at Singapore Mobile .Net Developers  meetup, under the topic “The three Awesome tools by Xamarin – Workbooks/Inspector/Profiler”!

So this blog post is a recap of the stuff I talked about! 😉

First of all here are the slides.

Here we go, the recap…

The three awesome tools by Xamarin

slide1

Last few months Xamarin has been busy releasing a lot of new updates and tools for us Developers, specially since the acquisition by Microsoft, they have been exponentially improving their platform and eco-system. 😀

So today I thought of picking up three awesome tool that has been released by Xamarin last few months, which are going to be extremely useful for Xamarin Mobile Development.

slide3

So to start off with…

Xamarin Workbooks!

slide4

Why do we need Xamarin Workbooks you asked? 😮

slide5

Now Imagine you’re someone who’s trying to learn Xamarin Mobile development or may be even C# dot net development? 😀

Could be someone trying to teach someone Xamarin or dot net or may be you’re trying to demo some awesome piece of code you implemented at a presentation, along with some documentation? 😉

Or simply you’re just trying out an experimenting some piece of code before you do some actual implementation in your actual project code?

Now in all of these stations, you have to open up your IDE, open up the documentations or presentations may be and most annoyingly you have to continuously switch in between them at all times. Not to mention having to recompile and run your code at the same time you switch back and forth. 😮

Oh well what a hassle is that?

To get rid of all that hassle, we have Xamarin Workbooks now! 😉

slide6

A perfect blend of documentation and code and immediate live preview results.

Xamarin Workbooks, is a prefect solution for experimenting with Xamarin and dot net code implementations and even as a learning tool for exploring code snippets and various kinds of implementations in Xamarin and dot net.

Perfect for creating teaching guides with a sweet side by side integration of code and documentation. Whenever you create or open up a Workbook, it creates a Sandbox environment for you to do your stuff, so you could accomplish your documentation aspect and coding aspect in one single place. 😉

slide7

So workbooks packs a bunch of awesome features, such as full fledged code editor with Roslyn IntelliSense, which has similar syntax coloring just like in Visual Studio. It has in-line compiler diagnostics support as well.

Attached with a rich text editor for you to add side by side code and documentation on the go. You could also easily search and add nuget packages as you go, just like you would do in Visual Studio, and instantly preview the results in console, or any mobile emulators as you have chosen.

You can easily save an share your workbooks with anyone and they could open it up and try out as they wish.

slide12

So Xamarin Workbooks supports dot net console/WPF implementations, Xamarin Android/iOS mobile development and even Xamarin Mac development scenarios. How cool is that eh! 😉

Xamarin Profiler!

slide14

Why do we need Xamarin Profiler you asked? 😮

slide15

Now as mobile developers we need to make sure we are giving a smooth intuitive user experience for our beloved users. So in order to do that, we need to make sure our app is fully optimized for the memory usage, process usage and various resource usage without causing any excessive lags or crashes.

And even some times during the development we come across these mysterious crashes without even hitting any debug points where we need more than just the debug logs to figure out what’s causing those mysterious crashes. 😮

Another aspect is that as mobile developers we need to always focus on the over flow of the resource usage in our application at run time so that we could do the necessary improvements in our code to reduce any excessive resource usage.

Something very important to keep in mind is that when we are dealing with Xamarin Mobile Development, we have to deal with both the Xamarin dot net environment and the Native environment at run time. In that case the available native profilers we have for android and ios can not help to analyze our xamarin dot net environment. So we need something better than just native profilers for our Xamarin Mobile applications.

As a solution for all those scenarios, we have Xamarin Profiler now! 😉

slide16

Xamarin Profiler is a tool that seamlessly integrated with your Xamarin Application, collects and displays information to analyze your application at run time.

This can easily be used for finding memory leaks, resolving performance issues, monitoring resource usage at the run time, and more over to polish up your mobile app before delivering to your users.

Fun fact, is that this tool is actually based on the Mono log profiler which is a command line profiler that they previously used to analyze Mono run time applications. So what they have done is, they’ve added a bunch of improvements to it and added this intuitive UI on top of it deliver this analytical information for us developers! 😀

slide17

So there are three key features or as they call them “instruments” that’s packed along with Xamarin Profiler. 😀

Allocations instrument is used for analyzing  the memory usage of your application at any given point of time at the run time.

Time Profiler instrument is used for tracking app performance, whereas it allows you to see which function took the longest to finish its execution.

Then we have the Cycles instrument, which provides you details with memory cycles occurred at the run time. May be I should explain it a bit further…

Memory Cycles: When you’re dealing with Xamarin Mobile applications, we have this environment of managed dot net environment and the un-managed native environment, sometimes due to our bad code a bunch of objects in the memory creates references to them selves in a circular manner, which could happen inside the dot net environment or most of the time in between the dot net and the un-managed environment. So in situations like that, the Garbage collector finds it hard to break through those circular references and release those objects, which results in those objects presisting in memory and the memory usage is only going to get increased. 🙂

So thanks to Xamarin Inspector we could easily identify those memory cycles and do the necessary changes in our code to eliminate them 😉

slide18

It also packs up these additional features allowing us to further drill down into details to analyze our application run time.

Xamarin Inspector!

slide20

Why do we need Xamarin Profiler you asked? 😮

slide21

As Mobile Developers we need to make sure we deliver a beautiful pixel perfect design for our end users, and specially according to my UX lead he’s going to haunt me in my nightmares if I don’t deliver a pixel perfect UI implementation. 😀

So we always have to do the tiny changes in padding or the height or the width or may be a tiny hex value in the color and so on, whereas every time we do a change we need to recompile the project and run.

And then even if you get the app to run, you still have to go navigate to the page that you just made the changes to, which takes a lot of time.

Now I’m aware of the existence of Xamarin Forms Previewer, but if you had already tried it out, we are well aware there’s a whole bunch of bugs and issues with it when it comes to complex UI designs, which has a whole bunch of custom renderers.

So for a solution to all the above scenarios, Xamarin has given us this awesome tool, Xamarin Inspector! 😀

slide22

An awesome tool that allows you to debug and analyze or modify your application UI at run time without having to recompile your code. 😉

Something really cool about this tool is that it gives this awesome exploded 3D layers view of your application UI. Which makes it very easy to analyze the rendered layers and get rid of any extra layers to improve performance.

slide23

Xamarin Inspector has two main features, first is the REPL access. REPL stands for Read, Evaluate, Print and Loop, which allows you to inject code to your application in real time.

Then the Visual Inspector allows you to interact with your UI hierarchy in real time in an intuitive 3D view.

So that you could make necessary changes to your UI in real time and see it instantly rendered on your emulator. 😉

Something very important to keep in mind is that, with the latest update for this tool, they are providing you direct Xamarin Forms support, so no longer you have to deal with the native-rendered properties, you could easily make changes to your Xamarin Forms properties on the fly.

Conclusion

slide25

Yep that’s it fellas! now get out there and build something awesome with Xamarin! 😀

Cheers!

-Udara Alwis, out! 😛

An improved ScrollView control for Xamarin Forms by me, myself and I…

Alright now when it comes to the default Xamarin Forms ScrollView, its pretty much generic and limited with the simple common attributes and behaviours, and it does not deliver any specific “cool” features with it.

What’s so cool about it?

So I thought of creating my own Custom ScrollView for Xamarin Forms using Custom Renderers, which would include the following awesome features,

Bouncy Effect – Yeah you gotta admit, the bounce effect of a native scrollview is pretty fun to play with, in a User’s perspective. So I thought of enabling this feature in my custom ScrollView even when the Child Element doesn’t exceeds the ScrollView boundaries… 😉
(PS: this effect is interpreted in native Android and iOS differently)

Disabling and Enabling Horizontal and Vertical Scroll Indicators – Now sometimes these scroll bar indicators are useful but there are times which we want to hide them, as it might look ugly on the UI in certain cases. So yeah let’s have some control over it shall we? 😀

Background Image – Of course who wouldn’t like a background Image on a Scroll view eh! 😉 Well to be specific we are going to add a Fixed Background Image for the ScrollView. And note that this background Image would be fixed, and will not be scrolling with the Content of the ScrollView. (I will do another post to enable that feature).

Yes behold, me, myself and I presenting the “BloopyScrollView” why the name “BloopyScrollView”? I don’t even know. lol 😛

Implementation

Alright let’s go ahead and create our Custom ScrollView Control in the PCL project. Along with the following properties, so that we could have direct control over the above said behaviours.

Alright now expect this to be longer, since I have added the properties as Bindable Properties, so you could use them in any MVVM scenario with ease. 😀

namespace WhateverYourNamespace
{
    public class BloopyScrollView : ScrollView
    {
        public static readonly BindableProperty IsHorizontalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsHorizontalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Horizontal scrollbar visibility
        /// </summary>
        public bool IsHorizontalScrollbarEnabled
        {
            get { return (bool)GetValue(IsHorizontalScrollbarEnabledProperty); }
            set { SetValue(IsHorizontalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsVerticalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsVerticalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Vertical scrollbar visibility
        /// </summary>
        public bool IsVerticalScrollbarEnabled
        {
            get { return (bool)GetValue(IsVerticalScrollbarEnabledProperty); }
            set { SetValue(IsVerticalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsNativeBouncyEffectEnabledProperty =
        BindableProperty.Create(
            nameof(IsNativeBouncyEffectEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            true,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Native Bouncy effect status
        /// </summary>
        public bool IsNativeBouncyEffectEnabled
        {
            get { return (bool)GetValue(IsNativeBouncyEffectEnabledProperty); }
            set { SetValue(IsNativeBouncyEffectEnabledProperty, value); }
        }


        public static readonly BindableProperty BackgroundImageProperty =
        BindableProperty.Create(
            nameof(BackgroundImage),
            typeof(ImageSource),
            typeof(BloopyScrollView),
            null,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Background Image of the ScrollView
        /// </summary>
        public ImageSource BackgroundImage
        {
            get { return (ImageSource)GetValue(BackgroundImageProperty); }
            set { SetValue(BackgroundImageProperty, value); }
        }
    }
}

 

There we go IsHorizontalScrollbarEnabled, IsVerticalScrollbarEnabled to disable/enable Horizonal and Vertical Scrollbars.

IsNativeBouncyEffectEnabled to control the Native Bouncy effect.

BackgroundImage to set the ImageSource for the ScrollView’s background Image. And make sure to provide a proper image for this hence we will be resizing the given image in our native renderer level to fit to the background of the ScrollView.(You will see in the next steps below)

Alright let’s head over to creating the Custom Renderers associated with our BloopyScrollView.

Something to keep in mind…

So if you’re a frequent reader of my blog, you may remember sometime ago I created an Extention class for handling Xamarin Forms Images in Native code level: https://theconfuzedsourcecode.wordpress.com/2016/12/12/an-awesome-image-helper-to-convert-xamarin-forms-imagesource-to-ios-uiimage-or-android-bitmap/

Why I’m bringing this up, is because we are going to be needing it for this project. You ask why? Because we need to convert the above BackgroundImage, which is of type Xamarin Forms ImageSource.

So we need to convert that ImageSource to native UIImage or Bitmap image respectively in our Custom renderer levels. 😉

So go ahead and grab that code real quick and add it to your Native Projects. 😀

iOS Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.iOS project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private UIImage _uiImageImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.ShowsVerticalScrollIndicator = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.ShowsHorizontalScrollIndicator = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (e.NewElement != null)
            {
                if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
                {
                    this.Bounces = true;
                    this.AlwaysBounceVertical = true;
                }

                if (((BloopyScrollView)e.NewElement).BackgroundImage != null)
                {
                    // retrieving the UIImage Image from the ImageSource by converting
                    _uiImageImageBackground = await IosImageHelper.GetUIImageFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage);
                }

                ((BloopyScrollView)e.NewElement).PropertyChanged += OnPropertyChanged;
            }
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
        {
            if (propertyChangedEventArgs.PropertyName == BloopyScrollView.HeightProperty.PropertyName)
            {
                // check if the Width and Height are assigned
                if (((BloopyScrollView)sender).Width > 0 & ((BloopyScrollView)sender).Height > 0)
                {
                    // resize the UIImage to fit the current UIScrollView's width and height
                    _uiImageImageBackground = ResizeUIImage(_uiImageImageBackground, (float)((BloopyScrollView)sender).Width, (float)((BloopyScrollView)sender).Height);

                    // Set the background Image
                    this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
                }
            }
        }

        // We need to override this to have the background image to be fixed
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
        }

        // Resize the UIImage
        public UIImage ResizeUIImage(UIImage sourceImage, float widthToScale, float heightToScale)
        {
            var sourceSize = sourceImage.Size;
            var maxResizeFactor = Math.Max(widthToScale / sourceSize.Width, heightToScale / sourceSize.Height);
            if (maxResizeFactor > 1) return sourceImage;
            var width = maxResizeFactor * sourceSize.Width;
            var height = maxResizeFactor * sourceSize.Height;
            UIGraphics.BeginImageContext(new CGSize(width, height));
            sourceImage.Draw(new CGRect(0, 0, width, height));
            var resultImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return resultImage;
        }
    }
}

 

Inside the method we are assigning the relevant properties of our BloopyScrollView to the native control properties.

The UIScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • ShowsVerticalScrollIndicator: Make the vertical scrollbar visible or hidden
  • ShowsHorizontalScrollIndicator: Make the horizontal scrollbar visible or hidden
  • Bounces: Always enable the native bounce effect on iOS UIScrollView
  • BackgroundColor: Allows to set the background color for the UIScrollView or set an Image as a pattern

Also you may have noted that we are converting our Image Source BackgroundImage to a UIImage using our extension.

And then when the Height and Width are set to the Control, we are resizing the Image to fit those properties and setting that as the Background of the UIScrollView through the UIColor.FromPatternImage() which allows us to set the image as a pattern throughout the canvas of the UIScrollView.

the strange tale of getting the UIScrollView’s Fixed background in Xamarin… :O

Notice that we are overriding the Draw(CGRect rect) method, this is to have the UIScroll Background Image to be fixed within the boundaries, and not to be spanned across the Content area.

Because usually if we set the BackgroundColor property, it will span across the Content area, but strangely if we override the Draw() method, BackgroundColor would only be contained within UIScrollView’s boundaries, without spanning across the Content area. This is something I figured out while playing around with the above implementation. 😀

Alright let’s jump into Android… 😀

Android Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.Android project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private Bitmap _bitmapImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.VerticalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.HorizontalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
            {
                this.OverScrollMode = OverScrollMode.Always;
            }

            if (((BloopyScrollView) e.NewElement).BackgroundImage != null)
            {
                // retrieving the Bitmap Image from the ImageSource by converting
                _bitmapImageBackground = await AndroidImageHelper.GetBitmapFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage, this.Context);

                // resize the Bitmap to fit the current ScrollView's width and height
                var _resizedBitmapImageBackground = new BitmapDrawable(ResizeBitmap(_bitmapImageBackground, this.Width, this.Height));

                // Set the background Image
                this.Background = _resizedBitmapImageBackground;
            }
        }

        // Resize the Bitmap
        private Bitmap ResizeBitmap(Bitmap originalImage, int widthToScae, int heightToScale)
        {
            Bitmap resizedBitmap = Bitmap.CreateBitmap(widthToScae, heightToScale, Bitmap.Config.Argb8888);

            float originalWidth = originalImage.Width;
            float originalHeight = originalImage.Height;

            Canvas canvas = new Canvas(resizedBitmap);

            float scale = this.Width / originalWidth;

            float xTranslation = 0.0f;
            float yTranslation = (this.Height - originalHeight * scale) / 2.0f;

            Matrix transformation = new Matrix();
            transformation.PostTranslate(xTranslation, yTranslation);
            transformation.PreScale(scale, scale);

            Paint paint = new Paint();
            paint.FilterBitmap = true;

            canvas.DrawBitmap(originalImage, transformation, paint);

            return resizedBitmap;
        }
    }
}

 

The Android ScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • VerticalScrollBarEnabled: Make the vertical scrollbar visible or hidden
  • HorizontalScrollBarEnabled: Make the horizontal scrollbar visible or hidden
  • OverScrollMode: Always enable the native bounce effect on Android ScrollView
  • Background: Allows to set the background drawable for the ScrollView

As you may have noticed we are converting our Xamarin Forms Image Source BackgroundImage to a Bitmap image using our extension.

Then we are resizing out Bitmap image according to the Width and Height of the ScrollView to fit to the full background to be wrapped around a BitmapDrawable and set to the Background of ScrollView.

There you go! 😀

Let’s use it… 😉

Alright now that’s done, let’s consume this in our PCL project.

<StackLayout Padding="10,0,10,0">

	<Label Text="Welcome to Xamarin Forms!"
		   VerticalOptions="Center"
		   HorizontalOptions="Center" />

	<local:BloopyScrollView 
	IsNativeBouncyEffectEnabled="True"
	IsVerticalScrollbarEnabled="False"
	IsHorizontalScrollbarEnabled="False">
	<local:BloopyScrollView.BackgroundImage>
	  <FileImageSource File="xamarinBackgroundImage.png"/>
	</local:BloopyScrollView.BackgroundImage>
	
			<Label
			  FontSize="22"
			  HeightRequest="400"
			  Text=
			  "Whatever your text content to be displayed." />
			  
	</local:BloopyScrollView>

</StackLayout>

 

As you can see I have inserted my BloopyScrollView in a StackLayout and as the content of the ScrollView I have added Label. Well you can add any content you want or set any Height or Width as you wish.

Notice that I have set IsNativeBouncyEffectEnabled to be True as I want to see the native Bouncy effect. Then I have disabled the Vertical and Horizontal Scrollbars from the properties we added earlier. Then finally I have added the BackgroundImage and set the FileImageSource to the ImageSource type, where as I have placed the image in the native Resource folder, as you would do with any defualt Xamarin Forms Image. 😉

Now let’s see the results… 😀

bloopscrollview-on-ios-lowq  bloopscrollview-on-android-lowq

Yaay! 😀

As we expected the Vertical and Horizontal Scrollbars are disabled and our ScrollView has full native bouncy effect accordingly.

Also you can see the Background Image nicely resized itself and fit to the background of the BloopyScrollView. 😀

Happy dance! lol

Recap Stuff…

Now there’s some stuff I wanted to recap, that is you may have noticed that when I was resizing the Image, I needed the Control’s Height and Width, and where I have acquired those properties are in two different places on each Android and iOS renderers.

To be specific I have accessed the Control’s Width and Height on Android right from the OnElementChanged method, but on iOS renderer I have accessed those values from the  OnPropertyChanged method’s Height property event. 

This is because of the differences of the Rendering cycling of Android and iOS, whereas on Android right at the firing of the Custom Renderer it assigns itself Width and Height. But on iOS we have to access them indirectly by waiting till those properties are set, by listening to the OnPropertyChanged event.

Get it on Github! 😀 XFImprovedScrollView

Cheers everyone!

Pass this on to another developer to make them smile! 😀
– Udara Alwis

Why MVVM is Awesome!

I used to be a code behind event driven loving developer! but since I found MVVM, I never looked back, MVVM all the way!

From Code-behind Event-driven addict to MVVM fanatic…

So for a developer who’s coming from a code behind event based implementation loving developer, I understand, adopting MVVM to your application could be pretty confusing and hectic at the beginning!

Because I know it very well by my own experience, whereas I used to be a stubborn noob developer in the good old days thinking Event Driven WinForms approach is the best way to developer software. Which led me to suffocate massively when the code base got bigger and bigger, having massive hard time debugging, maintaining and even upgrading programs I was coding. Honestly I couldn’t understand the cause for this at the beginning due to my stubborn mindset of praising code-behind even driven programming style.

Step 1:

Then when I got into my career I had to force myself to start using MVVM based implementation. And yes it was super confusing and troublesome to understand.

Step 2:

But trust me after a while, step by step,  you start to see how fun it is, makes you feel like wiring up some electronic circuit to get it to work, how all those components gets wired up each other while still having the modules separately.

Step 3:

And you will notice how easy it is to maintain and extend your code base… 😉

Short and sweet,

MVVM stands for Model View View-Model

and it’s AWESOME!

Here is why?

  • MVVM enable true separation between your User Interface(Views) and Logical Code(ViewModel/ Model)! Yes decoupling is ghuuud!
  • Easily handle events with Commands – ICommand
  • Never underestimate the power of INotifyPropertyChanged
  • Take the best use of Binding (View to ViewModel properties)
  • With ViewModel you can easily manipulate Model’s data as you wish and set them to be bound to any Views as you wish and vice versa. Yes it’s that flexible!
  • Yes, the ultimate portability of your project’s components
  • Testing made super easy as the separation between UI and Code behind logic
  • Extremely ease of maintenance and adding changes to your code base

So there you go, a short and sweet post I made during my free time! 😀

hope it helped anyone or may be inspired someone to make the switch! 😉

I am a Developer and I Code with ‪#‎VisualStudio‬ ! ;)

I code with Visual Studio 2

I am a Developer and I Code with #VisualStudio. 😀 Build your own Visual Studio profile today at aka.ms/myVisualStudio!
Yep that’s me, that hyper-active kid in the photo lol 😛
Kudos to whoever created this simply awesome tool. 😀
– Udara Alwis
[ÇøŋfuzëРSøurcëÇødë]

Few words about the ÇøŋfuzëÐ SøurcëÇødë Blogging Style ! ;)

Yes I am a Developer! A Software Engineer by career!

But truth be told, I’m not the typical type of software-engineer-developer-geek ! 😛

I’m a hyper-active, overjoyed, crazy enthusiastic, energized, optimistic human being! 😉

I often go on Adventures, Hiking, Running, Cycling and Basketball, also includes Socializing and talking to People in Public…

I run a lot ! literally like a mad man, and I’m addicted to it. It makes me feel free, refreshed, de-stressed, energized, hyped up, and allows me to push myself beyond the physical limitations. Hence it keeps reminding me that nothing is impossible as long as I keep on pushing myself without giving up.

I enjoy every single moment of my life, seeing the positive perspective of everything that happens around me. And I never regret any decisions I have ever made. I like making others happy and cheering up people around me is something I enjoy a lot. 😀

Yes! obviously I’m always cheered up! 😛 that’s probably the easiest way to recognize me from any crowd lol! 😉

I do a lot of crazy random stuff! 😀

I truly enjoy helping others, teaching others new stuff, I’m not very good at teaching though, but I enjoy engaging in such activities to the fullest.
So basically whenever I’m blogging the same chemical reactions fires up in my brain which is responsible for the above, thereby almost all the time my blog articles ends up being a hyper active conversation lol! 😛

So you may find my blog articles UNPROFESSIONAL most of the time! but I DO NOT CARE! Hence blogging programming articles is something I do for fun and I enjoy it insanely. 😉 And yes this is probably going to be one of the weirdest tech-blogs you have ever seen given my unprofessional-blogging-style! lol 😉
Well I couldn’t care less as long as I share the knowledge across the articles, in a very friendly, easy to understand manner for even a high school kid could understand.

So you got any complains about the ÇøŋfuzëÐ SøurcëÇødë Blogging Style? Don’t bother complaining! 😀 As ÇøŋfuzëÐ SøurcëÇødë wouldn’t ever care! 😛

Cheers!

Stay Awesome fellas! 😀

Oki Dokie… Let’s try out our Xamarin Forms AwesomeListView…

Hope you guy’s recall my previous post on Xamarin Forms Custom Listview with some added awesomeness… 😉 Where I unveiled a listview that is actually awesome ? 😀 Well as promised here is the article about the sample application I will be developing using my AwesomeListView.

Now for this article we will create a small Xamarin Forms app, which is going to load a bunch of dummy contacts to a listview… 😀

Let’s begin…

So this is how it’s all gonna stack up,

capture

As you can see above you need to create a Xamarin Forms project solution. And within that I have separated the code based on MVVM pattern, whereas we will be using the ObservableObject class as the base for handling properychanged and command events. Contacts Page shall be our View which we are gonna fit in our awesome-listview 😉 !

And yes hereby I’m gonna call it AwesomeListView ! 😀

Setting up the Data Source…

First create a Modal class called Contacts. This shall be the modal class for our Contacts items for the listview.

namespace WhateverYourNamespace.Models
{
    public class Contact
    {
        public String Name{ get; set; }
        public String Phone { get; set; }
    }
}

 

Now we need to create a tiny repository class, which will return a bunch of dummy data to be populated in out listview. Well don’t worry ! obviously I wasn’t going to hardcode that by myself, I’m a engineer for my degree certificate’s sake 😛 lol

So we are going to be using this tiny awesome library to generate our dummy data, Faker.Net.Portable ! Surprisingly enough its a pretty cool library which can populate real-like dummy data with ease. You can read all about it on my blog post about it, https://theconfuzedsourcecode.wordpress.com/2015/11/07/wanna-create-an-awesome-dummy-data-set/

Anyways go ahead and add that library to your project from Nuget Package Manager, to your PCL, Xam.Android, Xam.iOS and Xam.WinPhone…

With that now we can set up our data source repository as follows.

namespace WhateverYourNamespace.DataAccess
{
    public class ContactsRepository
	{
        public static List<Contact> FakeContactsList = new List<Contact>();

        public ContactsRepository() 
        {
            for (int i = 0; i < 100; i++)
            {
                try
                {
                    // Generating dummy data and adding to the list 

                    var name = Faker.Name.FullName();
                    var phone = Faker.Phone.CellNumber();

                    FakeContactsList.Add(new Contact { Name = name, Phone = phone });
                }
                catch (Exception)
                {

                }
            }
        }
    }
}

 

In our ContactsRepository class we are going to be having a List items source with a static reference, and in the runtime we will populate our fake data in the constructor and add them to the static list.. Pretty straight forward ! 😀

Setting up the ViewModel…

Now we need to set up our ViewModel classes for the Listview to be used, therefore we shall begin by creating the base ObservableObject class which is going to be an abstract with the INotifyPropertyChanged handlers.

namespace WhateverYourNamespace.Core
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public virtual event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

 

Now let’s dive into our ViewModel, whereas we shall be creating the ContactsPageViewModel which is to be used with the Awesome-Listview of ours. 😉 Now just for the case of article, I will provide you with section by section of the whole ViewModel as shown below… So if you are already writing the code while reading this article, I suggest you keep including the code snippets which will be given in this article, step by step just as it is.. 😉

Constructor and Private Values for the ViewModel

Below is the constructor and the private values to  be used in our ViewModel…

namespace WhateverYourNamespace.ViewModels
{
    class ContactsPageViewModel : ObservableObject
    {
        private readonly INavigation _navigation;
        private List<Contact> _repository;
        private ObservableCollection<Contact> _contactsList;
        private bool _isBusy;
        private bool _isFree;
        private bool _isLoadMoreEnabled;
        private bool _isDataListEmpty;
        private string _filterBy;
        private int _loadedCount;
        private Contact _selectedContact;

        public ContactsPageViewModel(List<Contact> repository, INavigation navigation)
        {
            LoadMoreContactsCommand = new Command(LoadMoreContacts);

            _repository = repository;
            _navigation = navigation;
            _loadedCount = 0;
            _filterBy = "FILTER1";
            IsBusy = false;
            _isDataListEmpty = false;
            _isLoadMoreEnabled = true;

            LoadMoreContacts();
        }
		
	// Properties Section //
		
	// Commands Section //
		
	// Methods Section //
     }
}

 

As you can see, we shall be passing in a List of Contacts as the Item Repository, which is to be used for providing data for each loading cycle of the list view. I have also instantiated a Command property there in the constructor, which shall be explained in the coming paragraphs of this article. And as for the rest of Private variables and their default values, you will get the idea in the next section…

// Properties // for the ViewModel

Below are the Properties which should be included in the above ViewModel class (right underneath the Constructor would be idea 😉 )

#region Properties

/// <summary>
/// Gets or Sets the ContactsList value
/// </summary>
public ObservableCollection<Contact> ContactsList
{
	get { return _contactsList ?? (_contactsList = new ObservableCollection<Contact>()); }
}

/// <summary>
/// Gets or Sets the Filter String value, used for filtering the loaded results...
/// </summary>
public string FilterBy
{
	get { return _filterBy; }
	set
	{
		_filterBy = value;
		FilterAndReLoadContacts();
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets the currently loaded items count
/// </summary>
public int LoadedCount
{
	get { return _loadedCount; }
	set
	{
		_loadedCount = value;
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets the Selected Contact Item in the list
/// </summary>
public Contact SelectedContact
{
	get { return _selectedContact; }
	set
	{
		_selectedContact = value;
		GoToContactDisplayPage();
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets the IsBusy value, used for disabling any UI Control while loading data...
/// </summary>
public bool IsBusy
{
	get { return _isBusy; }
	set
	{
		_isBusy = value;
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets the IsFree value, used for re-enabling any UI Control after loading data (opposite of IsBusy) ...
/// </summary>
public bool IsFree
{
	get { return _isFree; }
	set
	{
		_isFree = value;
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets IsLoadMoreEnabled value, used for disabling Load More button when no results available
/// </summary>
public bool IsLoadMoreEnabled
{
	get { return _isLoadMoreEnabled; }
	set
	{
		_isLoadMoreEnabled = value;
		OnPropertyChanged();
	}
}

/// <summary>
/// Gets or Sets the IsDataListEmpty value, used For displaying empty result set.
/// </summary>
public bool IsDataListEmpty
{
	get { return _isDataListEmpty; }
	set
	{
		_isDataListEmpty = value;
		OnPropertyChanged();
	}
}

#endregion

 

Those are the properties as said, and I have given a small description for each property and its use, so I hope I wouldn’t have to give much of an explanation here… 🙂 I hope those above properties may solve the mystery regarding the private methods used in the Constructor.

// Commands // for the ViewModel

Below is the command that we will be implementing in the ViewModel.

#region Commands

public ICommand LoadMoreContactsCommand { get; set; }

#endregion

 

Hope you remember we instantiated a command in the Constructor of our ViewModel, yes this is the command we are using there.

If you are done including the Commands let’s move into the Methods implementation.

// Methods // for the ViewModel

Below are the set of methods which should be included in the ViewModel.

#region Methods

private async void LoadMoreContacts()
{
	if (IsBusy)
	{
		return;
	}

	IsBusy = true;
	IsFree = false;

	try
	{
		await Task.Delay(2000);

		// Check if the data source is empty 
		if (_repository.Count == 0)
		{
			IsDataListEmpty = true;
			IsLoadMoreEnabled = false;

			IsBusy = false;
			IsFree = true;

			return;
		}

		// Check if all the items in the source are loaded to UI
		if (ContactsList.Count == _repository.Count)
		{
			IsLoadMoreEnabled = false;

			IsBusy = false;
			IsFree = true;

			return;
		}


		int LoadBeginIndex = 0;
		int LoadEndIndex = 10;

		// Setting the Begin Index for 2nd hit and forward
		if (ContactsList.Count != 0)
		{
			LoadBeginIndex = ContactsList.Count;
		}

		// Check if the Current Loading Rage is with in the data set size
		if (LoadEndIndex > (_repository.Count - ContactsList.Count))
		{
			LoadEndIndex = (_repository.Count - ContactsList.Count);
		}

		// Loading the selected data set to the UI
		var characters = _repository.GetRange(LoadBeginIndex, LoadEndIndex);
		foreach (var character in characters)
		{
			ContactsList.Add(character);
		}

		LoadedCount = ContactsList.Count;
	}
	catch (Exception ex)
	{

	}

	IsBusy = false;
	IsFree = true;
}

private async void FilterAndReLoadContacts()
{
	if (IsBusy)
	{
		return;
	}

	IsBusy = true;
	IsFree = false;

	try
	{
		// Include your Filtering algorithm ...

		// You could filter the ContactsList in 
		// any order you wish and reset it back to it
	}
	catch (Exception ex)
	{

	}

	IsBusy = false;
	IsFree = true;
}

private async void GoToContactDisplayPage()
{
	if (SelectedContact == null)
		return;

	//Code to navigate the user to any other new Page to view details of the selected item
}

#endregion 

 

Now as you can see above, LoadMoreContacts() is used for loading the next set of results from the Repository object and setting to the ListView. There you can see we are using IsBusy and IsFree properties which is to notify the interface that the background processing is happening, which you could use to wire up to some UI controllers and use them as you wish. 🙂 Also you may have noticed the Await Timers inside the method, well that was just to simulate the waiting of the data loading, just for this sample app.

Then I have included the FilterAndReLoadContacts() method just as a skeleton method for you to implement your  own Filtering mechanism.

GoToContactDisplayPage() method will be used to pop up the detailed view of the selected item, which will be called through the SelectedContact property value change.

That’s all for the ViewModel for our Awesome-ListView, next make sure you have set up my AwesomeList in your project…

Setting up the AwesomeListView …

Well if you haven’t yet set up my AwesomeListView, then you better head into my previous article and do that right now and come back to this article to continue. https://theconfuzedsourcecode.wordpress.com/2015/11/10/xamarin-forms-custom-listview-with-some-added-awesomeness/

Alright ! if that’s set up then let’s dive into the MVVM’s “View” code…

Setting up the View …

So we need to set up the View for our MVVM implementation right ? I suggest we create a small ContentPage and include our AwesomeListView in it and do the necessary bindings with the above ViewModel…

Go ahead and create ContactsPage view in your Views folder as follows.

namespace WhateverYourNamespace.Views
{
    class ContactsPage : ContentPage
    {
        ContactsPageViewModel _viewModel;

        AwesomeListView ListView_Contacts = new AwesomeListView(true);

        public ContactsPage()
        {
	    // Defining UI Controls and setting up Bindings
            
            this.Appearing += ContactsPage_Appearing;
        }

        private void ContactsPage_Appearing(object sender, EventArgs e)
        {
            if (ListView_Contacts.ItemsSource == null)
            {
                // Populating the data in Repository
                ContactsRepository repo = new ContactsRepository();

                // Creating the ViewModel with necessary parameters
                _viewModel = new ContactsPageViewModel(ContactsRepository.FakeContactsList, this.Navigation);

                // Setting the created ViewModel to this View
                this.BindingContext = _viewModel;
            }
        }
    }
}

 

Yes we need to create an instance of the ContactsPageViewModel and also an instance of our AwesomeListView. There you can see I’m passing in ‘true’ value to the contructor, which means I’m going to be using the ListView with a ‘Load More’ footer button. 😀

I recommend that inside the Page.Appearing method only we should be setting up our BindingContext as we can make sure that all the UI Controls are loaded, whereas you can see there in the ContactsPage_Appearing() method I’m creating the Datasource – ContactsRepository and passing it into the ViewModel’s constructor. Thereby ending the execution with setting the BindingContext to it.

Nope we are not done yet, we need to Initialization the UI controls inside the Constructor right ? including our AwesomeListView as follow… So replace the above Constructor with the following code snippet.

public ContactsPage()
{
	var ListItemTemplate = new DataTemplate(typeof(TextCell));
	ListItemTemplate.SetBinding(TextCell.TextProperty, "Name");
	ListItemTemplate.SetBinding(TextCell.DetailProperty, "Phone");

	ListView_Contacts.SetBinding(AwesomeListView.ItemsSourceProperty, "ContactsList");
	ListView_Contacts.SetBinding(AwesomeListView.SelectedItemProperty, "SelectedContact");
	ListView_Contacts.SetBinding(AwesomeListView.IsEnabledProperty, "IsFree");
	ListView_Contacts.SetBinding(AwesomeListView.IsBusyProperty, "IsBusy");
	ListView_Contacts.SetBinding(AwesomeListView.IsLoadMoreItemsPossibleProperty, "IsLoadMoreEnabled");
	ListView_Contacts.ItemTemplate = ListItemTemplate;

	ListView_Contacts.SetBinding(AwesomeListView.LoadMoreItemsFooterCommandProperty, "LoadMoreContactsCommand");

	Label lbl_ContactsEmptyAlert = new Label()
	{
		Text = "Sorry ! Contacts list is currently empty... Please check back later...",
		HorizontalOptions = LayoutOptions.CenterAndExpand,
		VerticalOptions = LayoutOptions.CenterAndExpand,
		FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
		XAlign = TextAlignment.Center
	};
	lbl_ContactsEmptyAlert.SetBinding(Label.IsVisibleProperty, "IsDataListEmpty");
	StackLayout StackLayout_ContactsEmptyAlert = new StackLayout
	{
		Children = { lbl_ContactsEmptyAlert },
		Padding = new Thickness(10, 0, 10, 5),
	};
	StackLayout_ContactsEmptyAlert.SetBinding(StackLayout.IsVisibleProperty, "IsDataListEmpty");
	
	Label lbl_LoadedCount = new Label()
	{
		FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
	};
	lbl_LoadedCount.SetBinding(Label.TextProperty, "LoadedCount", BindingMode.TwoWay, null, "Loaded {0} items ...");

	if (Device.OS != TargetPlatform.WinPhone)
	{
		this.Padding = new Thickness(5, Device.OnPlatform(5, 0, 0), 5, 5);
	}

	this.Content = new StackLayout
	{
		Children = 
		{
			StackLayout_ContactsEmptyAlert,
			new StackLayout
			{
				Children = 
				{ 
					lbl_LoadedCount
				},
				Padding = new Thickness(10, 0, 0, 0),
			},
			ListView_Contacts
		}
	};

	this.Appearing += ContactsPage_Appearing;
}

 

First we will be creating a small DataTemplate of TextCell, then we shall be initializing our AwesomeListView with the necessary bindings. As you can see above I have set up all the Bindable Properties of our AwesomeListView to the ViewModel’s properties and commands. ItemsSourceProperty, SelectedItemProperty, IsEnabledProperty are quite ordinary properties of a generic ListView, then you can see our custom properties being binded such as, IsBusyProperty, IsLoadMoreItemsPossibleProperty, LoadMoreItemsFooterCommandProperty which are the extra features provided by our AwesomeListView.

The lbl_ContactsEmptyAlert is a label that will show up when the Datasource is empty, based on the IsDataListEmpty property of the ViewModel. I have created a small Label lbl_LoadedCount to show how many items have been loaded to the ListView which also binded to the ViewModel’s LoadedCount property.

Now that should set up everything perfectly, let’s fire it up then…

Finally let’s FIRE IT UP… ! 😉

If you had implemented everything properly, there should be no compilation errors, therefore just hit 5 and watch the magic… 😀

// Here we go…

2

// While loading the data to ListView…

1

// After it reaches the end of the Data source…

3

// When the Data source is empty…

4

Some Wisdom…

Now after everything worked out beautifully, it’s all up to your how you are going to use this and improve it to display in your own App’s… 😉 Just a matter of your Imagination !

As I have mentioned I left the Filtering code blank for you to write your own algorithm, but if you find it hard, here is just a tip, set up a couple of buttons in the View and have them set the value of FilterBy in the ViewModel, where as in the Set event, we are calling the filtering method right ? there catch the certain string value and do the filtering based on that for the ContactsList in the ViewModel.

Inside the LoadMoreContacts() method you could even call a webservice of your choice and have a tiny pagination algorithm set up so you could load the data set by set…

Like I said it’s all just a matter of your Imagination ! 😉

Well there it goes folks, hope this post was helpful for you and prolly saved you some time… 🙂 Please share this among other developers as this may become handy for another developer as well, and you may save their precious time as well…

Cheers folks ! Stay Awesome ! 😀

 

Xamarin Forms Custom Listview with some added awesomeness… ;)

Let me make it obvious, are you looking for a Xamarin Forms Listview that could have awesome features such as Infinite Scrolling, Load More footer button, Activity Indicator, Data Source awareness, and so on ? Alrighto ! then keep on reading my friend… 😉

It’s about to go down! 😛

So there was this one day, I came across implementing a simple Listview with an infinite data loading, whereas when the user reaches the end of the listview scroll, it should automatically load more items to the listview and so on. And easy enough I recalled some article I read through Xamarin Weekly Newsletter sometime back, so my lazy self wanted to look it up and check out the implementation. http://www.codenutz.com/lac09-xamarin-forms-infinite-scrolling-listview/ and yes it was a great tutorial indeed, I ended up finishing the implementation in few hours.
But my boss man wanted me to add a “Load More items” button at the bottom of the listview, instead of having to load items automatically while scrolling.

Well well, it seemed like no more lazing around, and just to make it fun, I took this as an opportunity to create an awesome-Listview with both those capabilities included and few more added sweetness… 😉 So here I am sharing my code as usual… 😀

And yes I must admit that I got inspired by the www.codenutz.com infinite scroll listview and I used his implementation of infinite loading method code in my own improved listview, so a big shout out for the developer of that listview. 🙂 You can check his github from here. Codenutz.XF.InfiniteListView

behold the AwesomeListView …

Now I shall reveal the Awesome-ListView of mine… 😀 and yes of course I literally named it the AwesomeListView ! lol

Instead of chunks of the code, I shall post the entire code at once, so anyone could easily use it upon their wish.. 😉

namespace WhateverYourNamespace.Controls
{
    /// <summary>
    /// A simple listview that exposes a bindable command to allow infinite loading behaviour.
    /// Along with Footer 'Load more' items button functionality and Auto Disable functionality
    /// </summary>
    public class AwesomeListView : ListView
    {
        Button btn_LoadMoreItems;

        ActivityIndicator ActivityIndicator_LoadingContacts;

        /// <summary>
        /// Constructor - Pass in true/false to visible/hide Listview Footer 'Load more' items button
        /// </summary>
        /// <param name="IsLoadMoreFooterVisible"></param>
        public AwesomeListView(bool IsLoadMoreItemsFooterVisible = false)
        {
            ActivityIndicator_LoadingContacts = new ActivityIndicator
            {
                Color = Color.FromHex("#FF3300"),
                IsRunning = true,
                HorizontalOptions = LayoutOptions.FillAndExpand,
            };
            
            if (IsLoadMoreItemsFooterVisible)
            {
                // Setting up 'Load More' items footer

                btn_LoadMoreItems = new Button
                {
                    Text = "Load More... ",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("#0066FF"),
                    BorderRadius = 0,
                    BorderWidth = 0,
                    BorderColor = Color.FromHex("#0066FF"),
                    VerticalOptions = LayoutOptions.EndAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                };
                btn_LoadMoreItems.Clicked += btn_LoadMoreItems_Clicked;

                this.IsLoadMoreItemsPossible = true;

                this.Footer = new StackLayout
                {
                    Orientation = StackOrientation.Vertical,
                    Children = { ActivityIndicator_LoadingContacts, btn_LoadMoreItems },
                    Padding = new Thickness(0,5,0,5)
                };
            }
            else
            {
                // Setting up 'Infinite Scrolling' items

                ItemAppearing += AwesomeListView_ItemAppearing;

                this.Footer = new StackLayout
                {
                    Orientation = StackOrientation.Vertical,
                    Children = { ActivityIndicator_LoadingContacts },
                    Padding = new Thickness(0, 5, 0, 5)
                };
            }
        }

        #region UI Control Events

        /// <summary>
        /// Click event of Listview Footer 'Load More' items button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_LoadMoreItems_Clicked(object sender, EventArgs e)
        {
            if (LoadItemsMoreFooterCommand != null && LoadItemsMoreFooterCommand.CanExecute(null))
                LoadItemsMoreFooterCommand.Execute(null);
        }

        /// <summary>
        /// List View ItemAppearing event for infinite scrolling
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AwesomeListView_ItemAppearing(object sender, ItemVisibilityEventArgs e)
        {
            // Checking whether its possible to load more items
            if (!IsLoadMoreItemsPossible)
            {
                return;
            }

            var items = ItemsSource as IList;

            if (items != null && e.Item == items[items.Count - 1])
            {
                if (LoadMoreInfiniteScrollCommand != null && LoadMoreInfiniteScrollCommand.CanExecute(null))
                    LoadMoreInfiniteScrollCommand.Execute(null);
            }
        }

        #endregion

        #region Bindable Properties

        /// <summary>
        /// Gets or sets the property binding that defines whether the list has reached the 
        /// end of the items source thereby declaring its not possible to load more itmes... 
        /// </summary>
        public static BindableProperty IsLoadMoreItemsPossibleProperty = BindableProperty.Create<AwesomeListView, bool>(ctrl => ctrl.IsLoadMoreItemsPossible,
        defaultValue: false,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanging: (bindable, oldValue, newValue) =>
        {
            var ctrl = (AwesomeListView)bindable;
            ctrl.IsLoadMoreItemsPossible = newValue;
        });

        /// <summary>
        /// Gets or sets the property binding that defines whether the listview is busy 
        /// loading items in the background to the UI
        /// </summary>
        public static BindableProperty IsBusyProperty = BindableProperty.Create<AwesomeListView, bool>(ctrl => ctrl.IsBusy,
        defaultValue: false,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanging: (bindable, oldValue, newValue) =>
        {
            var ctrl = (AwesomeListView)bindable;
            ctrl.IsBusy = newValue;
        });

        /// <summary>
        /// Respresents the command that is fired to ask the view model to load additional data bound collection.
        /// </summary>
        public static readonly BindableProperty LoadMoreInfiniteScrollCommandProperty = BindableProperty.Create<AwesomeListView, ICommand>(bp => bp.LoadMoreInfiniteScrollCommand, default(ICommand));

        /// <summary>
        /// Respresents the command that is fired to ask the view model to load additional data bound collection.
        /// </summary>
        public static readonly BindableProperty LoadMoreItemsFooterCommandProperty = BindableProperty.Create<AwesomeListView, ICommand>(bp => bp.LoadItemsMoreFooterCommand, default(ICommand));

        #endregion

        #region Propertries

        /// <summary>
        /// Gets or sets the property value that defines whether the list has reached the 
        /// end of the items source thereby declaring its not possible to load more itmes...
        /// </summary>
        public bool IsLoadMoreItemsPossible
        {
            get { return (bool)GetValue(IsLoadMoreItemsPossibleProperty); }
            set
            {
                SetValue(IsLoadMoreItemsPossibleProperty, value);

                // Setting the value to button if it is available
                if (btn_LoadMoreItems != null)
                {
                    btn_LoadMoreItems.IsEnabled = value;

                    // Setting grey color for the button background in disabled state
                    if (!btn_LoadMoreItems.IsEnabled)
                    {
                        if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS)
                        {
                            btn_LoadMoreItems.BackgroundColor = Color.FromHex("#C0C0C0");
                            btn_LoadMoreItems.BackgroundColor = Color.FromHex("#C0C0C0");
                        }
                    }
                    else
                    {
                        if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS)
                        {
                            btn_LoadMoreItems.BackgroundColor = Color.FromHex("#0066FF");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets or sets the property value that defines whether listview is busy loading
        /// items in the background or not
        /// </summary>
        public bool IsBusy 
        {
            get { return (bool)GetValue(IsBusyProperty); }
            set
            {
                SetValue(IsBusyProperty, value);

                // Setting the value to ActivityIndicator
                if (ActivityIndicator_LoadingContacts != null)
                {
                    ActivityIndicator_LoadingContacts.IsVisible = value;
                }
            }
        }

        #endregion

        #region Commands

        /// <summary>
        /// <summary>
        /// Gets or sets the command binding that is called whenever the listview is reaching the bottom items area
        /// </summary>
        public ICommand LoadMoreInfiniteScrollCommand
        {
            get { return (ICommand)GetValue(LoadMoreInfiniteScrollCommandProperty); }
            set { SetValue(LoadMoreInfiniteScrollCommandProperty, value); }
        }

        /// <summary>
        /// <summary>
        /// Gets or sets the command binding that is called whenever user clicks on the 'Load More' footer button in the ListView
        /// </summary>
        public ICommand LoadItemsMoreFooterCommand
        {
            get { return (ICommand)GetValue(LoadMoreItemsFooterCommandProperty); }
            set { SetValue(LoadMoreItemsFooterCommandProperty, value); }
        }

        #endregion
    }
}

 

Alright, I shall discuss some of it’s added awesomeness from one after the other…

Constructor – As you can see above in our  AwesomeListView’s constructor I have defined a boolean parameter, which defines whether you need to use the ListView with the infinite scrolling enabled ? or whether you want to use the ListView with the Load More footer button enabled. This is very easy to use based up on your choice… 😉 When you pass in true it will enable the button and add it to the footer of the listview, along with its button clicks and commands. If not it will use the infinite scrolling feature.

UI Control Events – There are two event handlers, btn_LoadMoreItems_Clicked is for handling the click event of the footer button and the next one AwesomeListView_ItemAppearing is for handling the infinite scrolling. Inside that we have the logic for checking the appearance of the last item in the listview, and based on that the Load more command is fired. Also you may have noticed that it’s checking for a boolean value inside the event, which is to check whether the datasource has the capability to provide more items for the ListView to display. This can also be externally wired up by the ViewModel, and it’s very useful because the ListView won’t be wasting anytime firing up unnecessary data loading calls to the viewmodel when the datasource has no more data to provide.

Bindable Properties – We will be using those Bindable Propoerties to wire up the necessary functionality of this ListView to the outside code. IsLoadMoreItemsPossibleProperty defines whether it’s possible to load more data to the listview or not, based on the values provided by the ViewModel and IsBusyProperty is for defining whether the ListView is busy loading data in the background. And then comes the LoadMoreInfiniteScrollCommandProperty and LoadMoreItemsFooterCommandProperty, which are the Command Properties you could use for binding the ListView commands whether you need to call them based on infinite scroll or from the footer button command. You need to use the command property upon your  choice whether you need the infinite scroll listview or the footer button enabled listview. 😉

Propertries – I have defined a IsLoadMoreItemsPossible property which defines whether its possible to load more items from the data source in the viewmodel. This could be wired up through the above explained bindable property. There you may have noticed that in the setter method I’m setting the value directly to the footer button’s enable property, so that when the ViewModel informs the listview there are no more items to load in the data source, then the Footer load more items button will be disabled automatically. 😀 Then we have the IsBusy property which denotes whether the ListView is busy (actually the ViewModel) loading data from the background service or from the datasource to the UI. This is also used to make visible or hide the ActivityIndicator based on the passed in value of the ViewModel.

CommandsLoadMoreInfiniteScrollCommand and LoadItemsMoreFooterCommand, These are the Commands that will be used for loading data based on whether you have chosen the infinite scroll listview or the footer button enabled listview. These commands will be communicating through the bindable properties I have described above.

How to ?

Here is how you could use this in your own application if you ever find it confusing to implement this AwesomeListView… 😉

// Pass in the parameter defining whether you need the Infinite scroll or load more footer enabled
AwesomeListView ListView_Contacts = new AwesomeListView(true);

// Whatever your item template
var ListItemTemplate = new DataTemplate(typeof(TextCell));
ListItemTemplate.SetBinding(TextCell.TextProperty, "Name");
ListItemTemplate.SetBinding(TextCell.DetailProperty, "Phone");

// Setting the bindings for the AwesomeListView from your ViewModel as you please..
ListView_Contacts.SetBinding(AwesomeListView.ItemsSourceProperty, "ContactsList");
ListView_Contacts.SetBinding(AwesomeListView.SelectedItemProperty, "SelectedContact");
ListView_Contacts.SetBinding(AwesomeListView.IsEnabledProperty, "IsFree");
ListView_Contacts.SetBinding(AwesomeListView.IsBusyProperty, "IsBusy");
ListView_Contacts.SetBinding(AwesomeListView.IsLoadMoreItemsPossibleProperty, "IsLoadMoreEnabled");
ListView_Contacts.ItemTemplate = ListItemTemplate;

ListView_Contacts.SetBinding(AwesomeListView.LoadMoreItemsFooterCommandProperty, "LoadMoreContactsCommand");

 

Now how about you wanted to use the infinite scrolling functionality in our AwesomeListView ? It’s quite simple enough…

// Pass in the parameter defining whether you need the Infinite scroll or load more footer enabled
AwesomeListView ListView_Contacts = new AwesomeListView(false);

// Setting the bindings for the AwesomeListView from your ViewModel as you please..
ListView_Contacts.SetBinding(AwesomeListView.LoadMoreInfiniteScrollCommandProperty, "LoadMoreContactsCommand");

 

Change the constructor parameter to false and wire up the LoadMoreInfiniteScrollCommandProperty to your ViewModel. 😀

Here’s some screenshots of our AwesomeListView in action…

Untitled design

Anyhow I shall write another complete article along with a full example implementation of my AwesomeListView according to the MVVM pattern. Stay tuned fellas ! 😀

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time if you were ever intrigued by the same situation I went through… 🙂 Please share this among other developers and you may save another developer’s time as well… 😉

Cheers ! Stay Awesome ^_^ !