Introduction
In this tutorial we would be building our first app using Xamarin forms — Mood App. We would start with discussing a bit about Xamarin and Xamarin forms, then we would discuss its structure and how the designing a mobile app in Xamarin forms would work. We end it with discussing the architecture and coding out the mood which is a stack of buttons that gives quotes when a user clicks on the current mood he or she is feeling. Here is the link to the full code repository.
Prerequisites
- Visual Studio 2017 or 2019 with support for mobile development (if not previously available you could add mobile development workload when you run the installable file for visual studio again)
- Knowledge of C# and familiarity with XAML
What is Xamarin and Xamarin Forms?
Let’s talk a little bit about mobile development. The two major ways to build mobile apps are using native code or using cross platform methods. The Native Code means we develop iOS apps using Swift, and the android apps using Java or Kotlin on android studio. The cross platform methods means we would be developing both the iOS apps and Android apps using one language and they would be compiled into individual native apps by the system itself (actually a lil bit more complex than that). So for cross platform we have React Native (using JavaScript), Flutter (using dart), Xamarin (using C#).
still together?
Now let’s talk about Xamarin.
Xamarin,
Xamarin is an open-source platform for building modern and performant applications for iOS, Android, and Windows with .NET. Xamarin is an abstraction layer that manages communication of shared code with underlying platform code. Xamarin runs in a managed environment that provides conveniences such as memory allocation and garbage collection.
Basically meaning, we write code in .NET (C#), the Xamarin system does the magic (not really magic) and compiles it into the individual native code for the several platforms.
So where does Xamarin Forms comes in?
Well, Xamarin gives you the flexibility to still write only android apps using C# under the Xamarin.Android umbrella or the iOS app under the Xamarin.iOS tabernacle. But say you want both your apps to share code and some UI Design, then you use the Xamarin.Forms approach. Here is a diagramatic structure of Xamarin Forms from the Xamarin documentation.
So say you create a Xamarin Forms app in Visual Studio for your iOS and Android apps, you would have three projects; the one for Xamarin Forms (named after your project), the one for Xamarin.Android ({ProjectName}.Android) and the one for Xamarin.iOS ({ProjectName}.iOS).
One last thing to note, Xamarin could be used to build another type of app which is called Universal App, UWP (a Windows 10 app).
So what are we building again, A Mood App.
Our App, The Mood App
Concept:
The app is one wherein a user can click on any of the mood they are currently in and can get a quote that would address those feelings. So a user opens our app, sees a list of the moods, clicks on any of the mood and it displays an alert with the quote to address the mood — maybe elevate the feelings of someone that is sad.
The quote to be displayed is gotten from a json file we would collate ourselves.
Create the App and Examine the file structure
The first step is to create a Xamarin Project, and can be performed as thus.
- File > New > Project > Mobile App (Xamarin.Forms). Enter a name for the Project. Select Blank App.
The app file structure is now like this; MoodApp, MoodApp.Android, MoodApp.iOS. For the purpose of this tutorial, we would concerning ourselves with only the MoodApp project, specifically the MainPage.xaml (the view)and MainPage.xaml.cs (the code behind the view).
- Run the app, make sure to set either of MoodApp.Android or MoodApp.iOS as startup project. Though if you are not using a Mac OS, you could not set MoodApp.iOS as the startup project.
- If you open the MainPage.xaml, you should see the boilerplate code welcoming you to Xamarin. Remove that code from MainPage.xaml to remain only the ContentPage tag.
The UI
To build UI in Xamarin, we use XAML (Extensible Application Markup Language), and no they are were not developed exclusively for Xamarin nor same as XML. XAML is a language developed by Microsoft to build out the UI. It has been in use since the days of WPF.
Writing XAML is quite clear and if you have ever used HTML or XML, it would definitely be a smooth jump. And like the ML family it also makes use of square brackets and tags also.
Here is the UI we are building and a breakdown of the elements we would be using:
And here is the code
line 6–28 is the content you would be adding.
- line 7: It has the Label tag, where we would be putting the text we would be asking the user how they feel. Margin to put in some space and HorizontalOptions to put it at center.
I previously explained we would be using Grid and defining the rows using Grid.RowDefinitions.
- line 8: we open the Grid tag and set VerticalOptions as FillAndExpand to fill the entire width of the screen irrespective of the content.
- line 9 - 15: has the RowDefinition tag where we specify the height of each row. Here we used 1*, think of it like a special character that says it should take up the remain space. Now that we specify it on all the five rows, each row would take up equal spaces.
Next we are filling the rows with buttons and they follow the same pattern hence we would be discussing in detail only one of the button.
<Button x:Name=”SadBtn” Grid.Row=”0" BackgroundColor=”Black” ClassId=”Sad” TextColor=”White” Text=”Sad” Clicked=”SadBtn_Clicked”/>
- line 17–18: we gave it a name, SadBtn which helps us to recognize it. The Grid.Row property is used to specify the row, 0 implying that the first row. Because we need to extract the name of the particular button clicked, we are setting the ClassId to the name of the Mood of that button. And we have Clicked feature, which is an event and have named it SadBtn_Clicked. When adding the Clicked event, press enter on the suggestion that was brought out. It would immediately use an intellisense to help create a function with the same name in the code behind (i.e. MainPage.xaml.cs).
Recap: We set the ClassId property to name of the mood of that button so we could get the text in the code behind. We added a clicked event to respond when the button is clicked. Then we added other properties to beautify the button.
Run it again and you should see the view show up in your emulator.
Next, let us make it function.
The Logic
We would be writing the logic of the app in the MainPage.xaml.cs file. It is sometimes called the code behind.
What do we want the Logic to do then?
We want that when a user clicks the button, we get the text of that button (ClassId), then we load the json file where we have a list of the mood and corresponding quotes. Then we display an alert that matches the mood.
So: (1) we get ClassId, (2) loads the json collection of the corresponding list of quotes (3) select the quote that matches the mood selected (4) display an alert of the quote.
If you open MainPage.xaml.cs you should have something of this nature. This is event that is triggered when the individual button is clicked. And say you do not have it, no worries, just write it as above.
Create the Json file and add it
Add a json file to the MoodApp Project. Then add the content as above to it. Finally, check the properties of the json file and change the Build Action to Embedded Resource.
We have successfully added the json file now, but to read json file we would be using the Newtonsoft Json Package (right click the project to select Manage Nuget Package then search for the Newtonsoft Package, then install it).
We would also create the models to help us read the json file, like this:
Here is our model and it helps us to read the json file. Our model file structure matches our json file.
Get ClassId and Retrieve the corresponding Mood.
The above code would be perform in each of the block of the clicked event. Though we could repeat it in the number of clicked events that are present, but that would be outright bad code. Hence we would be setting it as a function on its own.
Let’s display an alert with the title and message we got from above.
yeah just one line. It is a function that Xamarin.Forms is giving us.
let do one final run at cleaning our code to have something like this:
Cleaned the functionalities into individual functions and having only line 3, (ShowMessage(sender)).
You can then copy the ShowMessage function while passing sender as parameter to the rest of the click methods.
Run it again and have your app displaying the corresponding quote when you select the mood.
and like that our current mood is Happpppy
Conclusion
In this tutorial we have written our first Xamarin App which displays a message when we select a mood. We have hardcoded the values of the message for corresponding mood, but we could extend it to talk to maybe videos APIs or other external APIs. Also, instead of displaying just an alert we could send the user to a new page.
I believe we have touch a few basics to get our foot wet in Xamarin.Forms. Have fun exploring. Here is the link to the full code repository.