Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

August 15

Live Webinar: Take your .NET Skills from the Desktop to Android and iOS

Register today to join me for my upcoming webinar, Xamarin University Presents: Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin on Tuesday, August 29, to see how to extend your desktop expertise to the mobile world. As a long-time desktop developer, I’ll share my personal experiences and technical best practices, giving you step-by-step guidance to make the jump to native Android and iOS development.


During the session, you’ll learn how to:

  • Use Visual Studio Tools for Xamarin and C# to design and build native apps for lots of devices and platforms
  • Map common desktop paradigms to mobile, including comparing desktop and mobile APIs
  • Optimize the UX / UI when porting your desktop app to a tablet or mobile device

You’ll also see sample code, get tips and tricks, and we’ll have Xamarin University instructors and mobile experts available to answer your questions live.

Register now to join us on August 29 at 9 am PT! Whether you’re a building commercial desktop apps, or apps for internal use, this session will give your mobile career a jumpstart.


We encourage all registrants to attend the webinar live, as we will be answering questions throughout the event. However, all registrants will receive a link to the recording, so please feel free to sign up even if you cannot join us that day.

The post Live Webinar: Take your .NET Skills from the Desktop to Android and iOS appeared first on Xamarin Blog.

August 14

Adding Storage to Mobile Apps with OneDrive for Business

Every app needs storage, whether it’s for storing a collection of the same type of records in Azure Mobile Service with Easy Tables, or a SQL Database exposed via Web Services. When the data is unstructured, NoSQL with Azure DocumentDB can be used. For scalability and high availability, Azure CosmosDb can be used in both the cases. In enterprise situations, however, where different types of documents need to be stored and shared with colleagues, the best solution is OneDrive for Business. OneDrive for Business is part of Office 365 and provides easy access across multiple Office 365 services. We learned previously how to integrate OneDrive for Business in mobile apps developed using Xamarin.

Since then, there have been changes to APIs and SDKs that have made this integration simpler. We’ll take a look at those changes in this blog post. You can find the repo for this post on GitHub.

Step 1: App Registration

To integrate OneDrive for Business with mobile apps, the app needs to be registered with the Azure Active Directory service. This will authenticate and authorize users while providing access to the resources. The process is the same as registering any other app with Azure Active Directory.

Visit https://apps.dev.microsoft.com/ and click on Add an app to get started. Name your app and continue, making sure you note the Application Id. Click on Add Platorm and select Native Application.

Ensure you define Delegated Permissions for the application to be able to access files stored on OneDrive for Business:

  • Files.Read
  • Files.Read.All
  • Files.Read.Selected
  • Files.ReadWrite
  • Files.ReadWrite.All
  • User.Read

Step 2: Calling APIs

Once the app is registered, create a Blank Xamarin.Forms application with the PCL code sharing strategy. Make sure that the profile selected for PCL is set to Profile7 by right-clicking the PCL project and selecting Properties > Build > General. Add two NuGet packages: Microsoft.Identity.Client and Microsoft.Graph.

Use the Microsoft Authentication Library (MSAL) to authenticate the user in the code-behind in App.xaml.cs.

using Microsoft.Identity.Client;
public static PublicClientApplication IdentityClientApp = null;
public static string ClientID = "4f91166f-c946-438f-8d07-33792251026d";
public static string[] Scopes = { "User.Read", "User.ReadBasic.All", "Files.Read", "Files.Read.All", "Files.ReadWrite", "Files.ReadWrite.All" };
public static UIParent UiParent = null;
public App()
   MainPage = new XamarinDrive.MainPage();
   IdentityClientApp = new PublicClientApplication(ClientID);
   MainPage = new NavigationPage(new MainPage());

After the authentication process is complete, create a GraphServiceClient object which will be responsible for further requests in the code-behind for MainPage.xaml.cs.

using Microsoft.Graph;
using Microsoft.Identity.Client;
private async Task CreateGraphClientAsync()
   try {
      Client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
               new DelegateAuthenticationProvider(
               async (requestMessage) => {
                         var tokenRequest = await App.IdentityClientApp.AcquireTokenAsync(App.Scopes, App.UiParent).ConfigureAwait(false);
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
                Me = await Client.Me.Request().GetAsync();
                Username.Text = $"Welcome {((User)Me).DisplayName}";
                return true;
       catch (MsalException ex){
            await DisplayAlert("Error", ex.Message, "OK", "Cancel");
            return false;

Using this GraphServiceClient and Graph Model, traverse through the Drive and get a list of items (files and folders) within the drive. Assign this list of items to the listview control in ListPage.xaml.cs.

using Microsoft.Graph;
var client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                async (requestMessage) =>
                   var tokenRequest = await App.IdentityClientApp.AcquireTokenSilentAsync(App.Scopes, App.IdentityClientApp.Users.FirstOrDefault());
                   requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
var data = await client.Me.Drive.Root.Children.Request().GetAsync();
var list = data.ToList();
FileList.ItemsSource = list;

This list of DriveItems will then be displayed on ListPage using the binding with ListView. When a user clicks on an item inside List, the file will be opened as requested. This can be achieved with the OnItemTapped event.

var item = ((DriveItem) e.Item);
   if (item.Folder != null)
      await DisplayAlert("Type", "Selected Item is a Folder!", "Ok");
      Xamarin.Forms.Device.OpenUri(new Uri(item.WebUrl));

Just like any Xamarin.Forms app is required to implement platform-specific functionality differently, follow the guide for each individual platform to implement authentication from here.

Step 3: Running the App

Run the app on a device or simulator and log in with your Office 365 credentials. The app will ask for appropriate permissions. Once those permissions are granted, the app will display the list of files.

Wrapping Up

OneDrive for Business, which is part of Office 365, allows users to store, share, and collaborate with different types of documents. Using Microsoft Graph Client Libraries and Microsoft Authentication Library, it’s easy to integrate various Office 365 services such as OneDrive. As usual, you can find the sample used in this blog post on GitHub.

The post Adding Storage to Mobile Apps with OneDrive for Business appeared first on Xamarin Blog.

August 11

Podcast: Contributing to Xamarin.Forms, C# 7, Input Validation, Android’s BottomNavigationView, and more!

In this episode of the Xamarin Podcast, James Montemagno and I cover the latest mobile .NET development news, including how to get started contributing to Xamarin.Forms, C# 7 tips & tricks, validating user input, Android’s BottomNavigationView, and new Xamarin releases. Be sure to download today’s episode from your favorite podcasting app!

Subscribe or Download Today

Keeping up with the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! Cohosts Pierce Boggan and James Montemagno cover topics relevant to Xamarin developers, from designing mobile apps to identity management. Be sure to subscribe to the Xamarin Podcast on iTunes, Google Play Music, Stitcher, or your favorite podcast app you use to ensure you don’t miss an episode.

The post Podcast: Contributing to Xamarin.Forms, C# 7, Input Validation, Android’s BottomNavigationView, and more! appeared first on Xamarin Blog.

August 10

Announcement: Clojure.spec implementation for Node.js

A few months ago I started implementing Speculaas, a Clojure.spec implementation for Node.js. This is the  announcement of a series of blog posts on this site in which I will show how to use this npm package for specification based testing of your code.

Have fun,


August 9

Payit Brings Peer-to-Peer Payments to Mexico with Mobile DevOps and the Cloud

Payit’s mobile apps are revolutionizing how Mexican residents pay bills and request and send money among friends and family. Initially a web-only way to pay rent, the founding team quickly realized that their customers were paying each other using the platform and developed Mexico’s first peer-to-peer payment network (available on Android and iOS), removing the need for wire transfers, checks, or visits to the ATM.

Today, Miguel Cervantes, Payit CTO, tells us how Payit has grown from a one-man development team to a fast-moving organization with an automated, bi-weekly release cadence to continuously ship high quality, secure apps to their passionate expanding customer base.

Tell us a little bit about your company and role.

Payit app on iPhoneWe started Payit a couple of years ago to solve a big problem for Mexico’s residents: cash. Because of its geography and lack of infrastructure, Mexico has the biggest “cost” of cash transactions in the world. Consumers spend 2.3 billion pesos and 48 million hours simply accessing cash (getting to an ATM, waiting in line, and paying associated fees), and Mexico’s welfare program spends a significant portion of its funds in dispersion and logistics costs. Less than 30% of Mexico’s adult population has a debit account, but the vast majority have a smartphone (see Fletcher School’s Institute for Business in the Global Context (IBGC) – Tufts University report to learn more about the cost of cash in Mexico).

We’re serving two distinct audiences or situations where people heavily rely on cash, even living in the biggest cities: young adults, typically between 18–34, who frequently need to pay or request funds from friends (roommates, trips, small loans) and small business owners and shopkeepers who need to collect payments for goods. This “informal market” of business owners represents over half of the Mexican economy, but they’re historically largely cash-based.

With Payit, our goal is to revolutionize the way we do things, making them easier, better, and faster. We allow anyone with a smartphone to send or receive money, and we free business owners to accept any form of digital payment, from a simple credit or debit cards today to crypto currencies in the future.

I’m Payit’s CTO, and I have experience with numerous languages and frameworks: a little Obj-C and Java, as well as web languages such as JavaScript / VB Script, but most of my experience is in writing enterprise-level C# applications for desktop (none targeting mobile platforms). Since our development team is small, I’m actively coding with our developers on a daily basis.

Tell us about your app; has it evolved over time?

Before Payit, we were a software development company. As many developers know, this is an extremely cyclical business; sometimes you have tons of work, sometimes you don’t.

In one of those “sometimes not” phases, we decided to start a service to satisfy one of our own needs: making rent payment easier. After we released, we quickly realized that many people were sending money to each other, not just their landlords, and saw an opportunity to tackle a much bigger market and help our whole country.

Our app is simple; it allows people to securely pay and collect funds through their mobile phones. Users create a login using their cellphone number or Facebook account, link their bank accounts and debit cards, and can immediately start sending and requesting money, view payment requests, and more. Before finalizing a transaction, users must enter a unique PIN to ensure all of their transfers are approved and safe.

Why did you choose Xamarin?

I analyzed many technologies, basing my decision on four main criteria:

  • Security and Stability: As a bank-like app, we needed to ensure that the technology let us have world-class security and stability. With Xamarin (and C#), we have flawless access to the key chain/key store and all .NET encryption functionality. .NET allows us to use several kinds of encryption systems with ease, including RSA1024 and AES256 to secure our communications (in addition to the SSL certificate).
  • Performance and Productivity: We wanted performance both on the device in the form of a native experience, as well as in our own development processes. Xamarin.Forms gives us that fully native look and feel and reduces our release cycles.
  • Scalability: We looked for technology with an active, growing community and great documentation.
  • TCO: We’re a start-up and keeping our burn rate as low as possible is top of mind. One language (C#) ruling both the backend and the front end reduces our need to staff and train a huge development team. Our developers move from the backend to the front end with ease, and share their knowledge and code between both worlds.

At the end of the day, we found our solution in Xamarin, particularly Xamarin.Forms.

How did you get up to speed with mobile development?

Our team used C# for desktop apps, so our ramp-up was easier. Plus, since everything is C#, we could share snippets and experiences across the team to get things done quickly.

What is the most compelling or exciting aspect of your app.

Beyond enabling mobile payments for the first time in Mexico, what makes us different is our commitment to mobile quality and security for our customers and fellow citizens. 

We’ve taken care to create a fully native UX and invested in mobile DevOps processes. On the security side, we store all personal bank information, including credit cards and account numbers, on the device (with encrypted distributed key methods and additional security layers), not on our servers.

We know that it’s not a matter of if, but when, we’ll face hack attacks, and having this distribution ensures we don’t have a “gold mine” of users’ financial data on our servers. In our eyes, the best person to have your personal and sensitive information is you.

Describe your development process and team structure; how long did it take you to release, from design to deploy?

Payit app on Android

We have four developers, including myself: one dedicated to the app (to me, it’s amazing that we only need one!), one dedicated to the core backend, one to the bank backend, while I usually switch between the app and the backend. A junior developer who helps us gather statistics and business analytics for reporting and a UX designer round out the team.

On the development side, everything is C#. We use Visual Studio 2017 Tools for Xamarin, Windows Server 2012 R2, and SQL Server Management Studio. We virtualize our test environment with Hyper-V, and all of our user profile data is stored in Microsoft SQL Server (transactions, profiles, sessions, friends, and wall events). I’ve worked with many different databases (MySQL, Derby, and Oracle) and found Microsoft SQL Server most smoothly runs big queries with a lot of data. 

From writing T-SQL queries to the integration with Visual Studio and availability of tools like SQL Server Management Studio (especially the Profiler) for debugging ORM generated queries, any data we want is immediately available.

For our mobile apps, we handle bank transactions, so it’s imperative that the app is bug free and makes users feel safe, or we’ll immediately lose their trust. We released our first version in 2016, but it would have taken eons without Xamarin. At the beginning of the project, we were a one-man army (me!), and having multiple languages and multiple IDEs would have taken me years to learn, code, debug, and deploy. Today, we share 98% of our code across Android and iOS (we have a few custom renderers that use C# native APIs).

As I mentioned, we’ve invested in mobile DevOps processes, including Visual Studio Mobile Center Preview for CI, and we release a new build daily, with a beta candidate for our internal testers every Thursday. Our release frequency depends on what we want to achieve; after a big new release, we typically ship updates every two weeks.

With each production release, HockeyApp crash reports and statistics help us understand what’s happening with the app; if it’s running correctly, how many users are crash-free, which issues are happening most frequently, and so forth. We use this information to learn and consistently improve.

What have your users said about your app? 

We have 60K active users and everyone we talk to loves the app, but we’re happier that more than 70% of our users come from referrals.

Our users don’t just like our app, they’re so passionate about it they share it with their friends! For an app like ours, virality is critical.

What’s your team planning to build next? Why?

We have a lot planned. Our goals have always been extremely ambitious. We’ve achieved great milestones, but still have a lot of work to do.

We’re in the process of migrating our .NET Framework to .NET Core, and we’re researching the best Azure Machine Learning algorithms to replace our existing “State Machine AntiFraud System” (what we’ve named our in-house system, which limits us to simple rules). We want to combine our experience and expertise with Azure Machine Learning and Azure infrastructure to create a peer-to-peer specific antifraud system that learns from our users.

Going forward, we’d also like to incorporate chatbots and a more conversational UI.

What advice do you have for developers or organizations who are just starting mobile development?

“Cross-platformize” your projects! Don’t be afraid of cross-platform native solutions. For us, our path changes a lot day-to-day. Because we share so much code across platforms, we’re able to quickly address changes in our market and the needs of our users. 

As a new developer, you’ll save a lot of time and money by not learning platform-specific languages and, instead, focusing on reaching as many platforms as possible as quickly as possible. The future of app development is the ability to run on every single device, and the less code you have to write, the better.

Lastly, platform-specific look and feel (UX) matters: users will recognize native quality, or non-native quality, and this has large impacts on your engagement/retention.
Visit xamarin.com/download to get started and explore xamarin.com/customers to get inspired.

The post Payit Brings Peer-to-Peer Payments to Mexico with Mobile DevOps and the Cloud appeared first on Xamarin Blog.

August 8

Validation in Xamarin.Forms Enterprise Apps

animationWe released an eBook this past May on Enterprise Application Patterns using Xamarin.Forms. The eBook focuses on core patterns and architectural guidance for developing Xamarin.Forms enterprise apps that are easier to test, maintain, and evolve. Guidance is provided on how to implement the Model-View-ViewModel (MVVM) pattern, dependency injection, navigation, validation, and configuration management, while maintaining loose coupling. In addition, there’s also guidance on performing authentication and authorization with IdentityServer, accessing remote data from containerized microservices, and unit testing.

This blog post explores validation in Xamarin.Forms enterprise apps. There are, of course, many approaches that can be taken to validation. What’s presented here is the validation approach taken in the eShopOnContainers mobile app, which is extensible, easily unit testable, and supports data binding and property change notification.


Any app that accepts input from users should ensure that the input is valid. An app could, for example, check for input that contains only characters in a particular range, is of a certain length, or matches a particular format. Without validation, a user can supply data that causes the app to fail. Validation enforces business rules, and prevents an attacker from injecting malicious data.

In the context of the Model-ViewModel-Model (MVVM) pattern, a view model or model will often be required to perform data validation and signal any validation errors to the view so that the user can correct them. The eShopOnContainers mobile app performs synchronous client-side validation of view model properties and notifies the user of any validation errors by highlighting the control that contains the invalid data, and by displaying error messages that inform the user of why the data is invalid. The following diagram shows the classes involved in performing validation in the eShopOnContainers mobile app:

View model properties that require validation are of type ValidatableObject<T>, and each ValidatableObject<T> instance has validation rules added to its Validations property. Validation is invoked from the view model by calling the Validate method of the ValidatableObject<T> instance, which retrieves the validation rules and executes them against the ValidatableObject<T> Value property. Any validation errors are placed into the Errors property of the ValidatableObject<T> instance, and the IsValid property of the ValidatableObject<T> instance is updated to indicate whether validation succeeded or failed.

Property change notification is provided by the ExtendedBindableObject class, and so an Entry control can bind to the IsValid property of the ValidatableObject<T> instance in the view model class to be notified of whether or not the entered data is valid.

Specifying Validation Rules

Validation rules are specified by creating a class that derives from the IValidationRule<T> interface, which is shown in the following code example:

public interface IValidationRule<T>
    string ValidationMessage { get; set; }
    bool Check(T value);

This interface specifies that a validation rule class must provide a boolean Check method that is used to perform the required validation, and a ValidationMessage property whose value is the validation error message that will be displayed if validation fails.

The following code example shows the IsNotNullOrEmptyRule<T> validation rule, which is used to perform validation of the username and password entered by the user on the LoginView when the eShopOnContainers mobile app is configured to use mock services:

public class IsNotNullOrEmptyRule<T> : IValidationRule<T>
    public string ValidationMessage { get; set; }
    public bool Check(T value)
        if (value == null)
            return false;
        var str = value as string;
        return !string.IsNullOrWhiteSpace(str);

The Check method returns a boolean indicating whether the value argument is null, empty, or consists only of whitespace characters.

Adding Validation Rules to a Property

In the eShopOnContainers mobile app, view model properties that require validation are declared to be of type ValidatableObject<T>, where T is the type of the data to be validated. The following code example shows an example of one such property:

public ValidatableObject<string> UserName
        return _userName;
        _userName = value;
        RaisePropertyChanged(() => UserName);

For validation to occur, validation rules must be added to the Validations collection of the ValidatableObject<T> instance, as demonstrated in the following code example:

private void AddValidations()
    _userName.Validations.Add(new IsNotNullOrEmptyRule<string> 
        ValidationMessage = "A username is required." 

This method adds the IsNotNullOrEmptyRule<T> validation rule to the Validations collection of the ValidatableObject<T> instance, including a value for the ValidationMessage property, which specifies the validation error message that will be displayed if validation fails.

Triggering Validation

Validation can be triggered manually for a view model property. For example, this occurs in the eShopOnContainers mobile app when the user taps the Login button on the LoginView, when using mock services. The command delegate calls the MockSignInAsync method in the LoginViewModel, which invokes validation by executing the Validate method, which in turn invokes the ValidateUserName method:

private bool ValidateUserName()
    return _userName.Validate();

The ValidateUserName method performs validation of the username entered by the user on the LoginView, by invoking the Validate method on the ValidatableObject<T> instance. The following code example shows the Validate method from the ValidatableObject<T> class:

public bool Validate()
    IEnumerable<string> errors = _validations
        .Where(v => !v.Check(Value))
        .Select(v => v.ValidationMessage);
    Errors = errors.ToList();
    IsValid = !Errors.Any();
    return this.IsValid;

This method clears the Errors collection, and then retrieves any validation rules that were added to the object’s Validations collection. The Check method for each retrieved validation rule is executed, and the ValidationMessage property value for any validation rule that fails to validate the data is added to the Errors collection of the ValidatableObject<T> instance. Finally, the IsValid property is set, and its value is returned to the calling method, indicating whether validation succeeded or failed.

Validation is also automatically triggered whenever a bound property changes. For more information, see Triggering Validation when Properties Change.

Displaying Validation Errors

The eShopOnContainers mobile app notifies the user of any validation errors by highlighting the control that contains the invalid data with a red line, and by displaying an error message that informs the user why the data is invalid below the control containing the invalid data. The following screenshot shows part of the LoginView in the eShopOnContainers mobile app when a validation error is present:

Highlighting a Control that Contains Invalid Data

The LineColorBehavior attached behavior is used to highlight Entry controls where validation errors have occurred. The following code example shows how the LineColorBehavior attached behavior is attached to an Entry control:

<Entry Text="{Binding UserName.Value, Mode=TwoWay}">
        <OnPlatform x:TypeArguments="Style"
          iOS="{StaticResource EntryStyle}"
          Android="{StaticResource EntryStyle}"
          WinPhone="{StaticResource UwpEntryStyle}"/>

The Entry control consumes an explicit style, which is shown in the following code example:

<Style x:Key="EntryStyle"
       TargetType="{x:Type Entry}">
    <Setter Property="behaviors:LineColorBehavior.ApplyLineColor"
            Value="True" />
    <Setter Property="behaviors:LineColorBehavior.LineColor"
            Value="{StaticResource BlackColor}" />

This style sets the ApplyLineColor and LineColor attached properties of the LineColorBehavior attached behavior on the Entry control. When the value of the ApplyLineColor attached property is set, or changes, the LineColorBehavior attached behavior executes the OnApplyLineColorChanged method, which adds or removes the EntryLineColorEffect class to the Entry‘s Effects collection. For more information about the EntryLineColorEffect class, see Highlighting a Control that Contains Invalid Data.

The Entry control also has a DataTrigger added to its Triggers collection. The following code example shows the DataTrigger:

<Entry Text="{Binding UserName.Value, Mode=TwoWay}">
            Binding="{Binding UserName.IsValid}"
            <Setter Property="behaviors:LineColorBehavior.LineColor" 
                    Value="{StaticResource ErrorColor}" />

This DataTrigger monitors the UserName.IsValid property, and if it’s value becomes false, it executes the Setter, which changes the LineColor attached property of the LineColorBehavior attached behavior to red.

Displaying Error Messages

The UI displays validation error messages in Label controls below each control whose data failed validation. The following code example shows the Label that displays a validation error message if the user has not entered a valid username:

<Label Text="{Binding UserName.Errors, Converter={StaticResource FirstValidationErrorConverter}"
       Style="{StaticResource ValidationErrorLabelStyle}" />

Each Label binds to the Errors property of the view model object that’s being validated. The Errors property is provided by the ValidatableObject<T> class, and is of type List<string>. Because the Errors property can contain multiple validation errors, the FirstValidationErrorConverter instance is used to retrieve the first error from the collection for display.


Enterprise Application Patterns using Xamarin.Forms focuses on core patterns and architectural guidance for developing Xamarin.Forms enterprise apps that are easier to test, maintain, and evolve. The eBook also ships with a sample application, the eShopOnContainers mobile app, which performs synchronous client-side validation of view model properties and notifies the user of any validation errors by highlighting the control that contains the invalid data, and by displaying error messages that inform the user why the data is invalid.

The post Validation in Xamarin.Forms Enterprise Apps appeared first on Xamarin Blog.

August 7

Exploring Android’s Bottom Navigation View

The debate over whether tabs should go on the top or the bottom of a screen has raged for nearly a decade. Android has always preferred to use tabs as a filtering mechanism on the top of a page, while iOS has used bottom tabs as the main source of navigation. Now, with the addition of the Bottom Navigation View in the Support Design library, Android developers have the choice of where their main navigation comes from in their applications.

Bottom navigation bars make it easy for your users to navigate through your top-level views with a single tap, compared the the navigation drawer that flies out from the side and has been a standard when there are a lot of different sections to an app. Today, I’ll walk through when it’s best to use bottom navigation in your app, how to implement it, and how to customize it to your liking.

The core experience of bottom navigation is designed for use on mobile phone devices that allows users to swap between pages easily. Some questions for if you should use bottom navigation are:

  • Does your app have 3–5 top-level pages?
  • Do your top-level pages need direct access?

If your application has more than five pages, it’s best to stick with the navigation drawer; if you have less than three, stick with standard top tabs.

Getting Started

To get started with the new Bottom Navigation View, we’ll want to make sure that we have our Android application updated with an AppCompat Activity and upgraded to the latest Support Libraries. With that, we can now install the Xamarin.Android.Support.Design NuGet package (current version 25.3.1) into our Android project at our set up.

Adding Tab/Menu Items

We must define the items that will be displayed before we add the BottomNavigationView control. This is controlled similarly to the NavigationDrawer, with a menu defined in xml. We can create a new menu folder in the Resources directory and add a new xml file. I created bottom_navigation_main.xml in Resources/menu/ and downloaded a few tab icons from the Android Asset Studio, which are 24dp x 24dp.


Adding a Bottom Navigation View

Bottom navigation works by replacing fragments when one of the items is selected. This means that our Android xml should also have a FrameLayout to swap in and out the fragments that will be displayed. Our xml will look something like this in its basic form:


We can define an elevation so the bottom navigation is lifted off the page with a nice drop shadow, and we define our items in the navigation view with the menu property that is referencing the menu we created earlier.

As we can see, the default will automatically apply our primary color and gray out the deselected items.

Handling Click Events

Now it’s time for us to actually handle the click events and set our content. In this example, I have three different fragments that simply load an Android xml file that displays the current index it’s on. We can create a simple method to replace the current fragment based on the ID that was set in the menu xml in our Main Activity:

void LoadFragment(int id)
    Android.Support.V4.App.Fragment fragment = null;
    switch (id)
        case Resource.Id.menu_home:
            fragment = Fragment1.NewInstance();
        case Resource.Id.menu_audio:
            fragment = Fragment2.NewInstance();
        case Resource.Id.menu_video:
            fragment = Fragment3.NewInstance();
    if (fragment == null)
        .Replace(Resource.Id.content_frame, fragment)

Now we can load our xml, find the BottomNavigationView, and register for a NavigationItemSelected event:

BottomNavigationView bottomNavigation;
protected override void OnCreate(Bundle bundle)
    var toolbar = FindViewById(Resource.Id.toolbar);
    if (toolbar != null)
    bottomNavigation = FindViewById(Resource.Id.bottom_navigation);
    bottomNavigation.NavigationItemSelected += BottomNavigation_NavigationItemSelected;
    // Load the first fragment on creation
private void BottomNavigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)

Adding Color

Google’s recommendation is to simply use the default white or black background color and primary tint of icons if your app is using default themes and your Toolbar is already tinted. If you wish to set the color of the bottom navigation, then it’s recommended to make the icon and text of the current action black or white. There are two additional properties, app:itemIconTint and app:itemTextColor, that can be set to handle this. Setting them directly to a specific color is what you probably think you want to do, but an immediate issue will present itself where it also sets the deselected state to the same color. For instance, if I set these three properties:


To fix this, we just have to create a selector defined in our drawable folder that will set the color based on the state in a new xml file; I called mine nav_item_colors.xml:


Now, back in our BottomNavigationView, we can use the new selector colors:


Absolutely lovely!

Learn More

To learn more about bottom navigation in Android, be sure to read through the Material Design Guidelines for all the “dos and don’ts” of using it. You can also grab a full sample and other samples of navigation from my GitHub repo.

The post Exploring Android’s Bottom Navigation View appeared first on Xamarin Blog.

August 4

A Beginner’s Guide for Contributing to Xamarin.Forms

Xamarin.Forms has been open source for over a year now. In that time, we’ve accepted over 700 pull requests and received many more. Have any of those been yours? If not, this is your invitation to participate! In this article, I’ll outline what kinds of contributions we are looking for and provide a guide to submitting your first bug fix.

What Contributions Will We Accept

In short, we’ll entertain anything that makes the Xamarin.Forms product better in terms of stability, quality, and capability. This may take the shape of:

  1. Bug fixes
  2. Feature implementations
  3. Tests
  4. Readme and Wiki articles or updates

Before you start opening Pull Requests on the GitHub project, there are some prerequisites.

Sign the .NET Foundation Release

At the time you submit a Pull Request, a .NET Foundation bot will check to make sure you’ve signed a Contribution License Agreement. If you haven’t, you’ll be prompted to do so. We cannot accept any contributions until this is completed.

Review the Coding Style Requirements

We adhere to the .NET Foundation style guide with a few exceptions:

  • Don’t use private as that’s the default protection level.
  • Use hard tabs instead of spaces
  • Limit lines to a max of 120 characters

For guidance on implementing some of these in your Visual Studio installation, check our readme.

Let’s Focus on Bug Fixes

Have you found a bug and have a fix you want to contribute? Awesome! Before you go too far, do a quick search on Bugzilla to see if there are any reports of the same issue. When searching for Xamarin.Forms, choose the Advanced Search option and:

  • Classification: Xamarin
  • Product: Xamarin.Forms
  • Component: None or All to search broadly
  • Status: All

If there is a matching issue and it’s is marked In Progress, then someone is already working the issue. If a PR is referenced on the issue, then it’s likely pending merge on GitHub. When the issue is Resolved and Fixed, then a Pull Request has been merged to address the issue. Currently, to see if it has been released yet and in which version you’ll need to search our release notes. We have a plan to improve that in the coming weeks.

If there’s a bug in any other incomplete state, or no bug report at all, then you’re in luck and ready to proceed!

Xamarin.Forms Solution Orientation

As you start exploring the Xamarin.Forms solution, it may seem a by daunting. I’ll demystify that for you and show you where to focus your attention.

Control Gallery/
These projects comprise a gallery application including all of the Xamarin.Forms controls available, and more importantly host bug reproductions with UITests inline. When working on fixing a bug, or just to investigate how a control is expected to work, this bare bones but functional app is where you want to look.

Pages Gallery/
As the name implies, this is another gallery application, but this time for the DataPages implementation.

These projects contain the platform specific implementations of services and most importantly UI controls. When Xamarin.Forms renders a Label on iOS it runs the Xamarin.Forms.Platform.iOS/Renderers/LabelRenderer.cs. On Android you’ll get Xamarin.Forms.Platform.Android/Renderers/LabelRenderer.cs, or if you’re using FastRenderers Xamarin.Forms.Platform.Android/FastRenderers/LabelRenderer.cs. When adding controls or fixing controls related bugs, this is where you’ll effect those changes.

When looking for core implementations of abstract controls, layouts, bindings, triggers, App Links, and other non-platform specific code, search these projects.

Xamarin.Forms.Maps/ and Xamarin.Forms.Xaml/
These folders are self-explanatory. You probably won’t spend too much time in those projects unless you happen to really understand those domains.

Fixing a Bug

  • Clone the Xamarin.Forms code from GitHub master branch or pull to make sure you have the latest.
  • Create a new branch to host your changes
  • Open the Xamarin.Forms solution and navigate to the Control Gallery > Xamarin.Forms.Controls.Issues > Xamarin.Forms.Controls.Issues.Shared
  • Use the _Template.cs to start a new case following the established naming convention of “Bugzilla######.cs” where ###### is the issue id in Bugzilla.

using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
using Xamarin.UITest;
using NUnit.Framework;
namespace Xamarin.Forms.Controls.Issues
	[Preserve(AllMembers = true)]
	[Issue(IssueTracker.Bugzilla, 1, "Issue Description", PlatformAffected.Default)]
	public class Bugzilla1 : TestContentPage // or TestMasterDetailPage, etc ...
		protected override void Init()
			// Initialize ui here instead of ctor
			Content = new Label
				AutomationId = "IssuePageLabel",
				Text = "See if I'm here"
		public void Issue1Test ()
			RunningApp.Screenshot ("I am at Issue 1");
			RunningApp.WaitForElement (q => q.Marked ("IssuePageLabel"));
			RunningApp.Screenshot ("I see the Label");

Implement your reproduction case here. If it’s a more complex case, refer to other issues in this project to find something similar and follow that pattern. In the end you should have a reproduction that demonstrates the problem you are working to solve.

  • Select a Control Gallery target project to run on simulator or device.

You should see your repro happening. If not, then it would appear the issue is fixed already.

  • Implement your fix and retest the repro.
  • Implement a UITest in the reproduction file. If you’re not a UITest pro, again reference some of the other fixes in the source. Once you submit the Pull Request, the tests will be run automatically.

You’re now ready to create a Pull Request. From within your IDE or Git tool of choice, create a Pull Request against the Xamarin.Forms remote on GitHub. This process should take you to the GitHub Pull Request page and populate with the Xamarin.Forms Pull Request template. We ask that you fill out everything you can, and omit anything that doesn’t apply.

What is the current behavior and what is the expected behavior.

List any and all Bugzilla reports that this applies to

API Changes
If the surface area of any class changed when making this fix, note the changes here. These may indicate breaking or behavioral changes for other users and their legacy applications.

Indicate if you have included tests. If no tests are required or the issue is too difficult to test with a UITest, note that.

And that’s it. Submit the Pull Request and we’ll review it. If there are questions or concerns, the team will submit comments and make requests on code. This review process may feel clinical, so don’t take it personally. Speaking for myself, it’s been a great learning experience to work through the Pull Request process on open source projects, and in nearly every case my contributions have eventually been accepted.

It is also extremely helpful to us and other users if you copy the url to the Pull Request and note it on the referenced Bugzilla issues.

Adding Features
Before you start working on a feature, check out the public Xamarin.Forms Roadmap and do a search of the Evolution forum where we discuss specifications for possible new features and other changes. If you don’t see the feature already covered, open a proposal on the Evolution forum and offer to implement it. The Xamarin.Forms engineering team will review the proposal and provide feedback.

What should you do if you are comfortable implement on one platform, but don’t know enough to implement the rest of the platforms? Go ahead and open the proposal and invite others to participate.

Tests and Wiki
As mentioned, we welcome contributions in these areas as well. We have a several projects for UITests as well as Unit Tests. We have fairly good coverage, but it could always be better. It’s important to test the right things, so if you have any questions please ask.

Our documentation team continues to do amazing work on our developer guides and the API documentation. If you spot any inaccuracies or have suggestions, use the “I have a problem” button in the sidebar and send us details.

If you have a wiki contribution that doesn’t quite fit into those documentation categories, let me know and we’ll consider building up the wiki.

Happy Contributing!

I hope you’ll consider contributing to Xamarin.Forms. There’s nothing quite like the satisfaction of having your pull request merged and knowing you’ve just helped out a huge community of amazing developers.

For more information and to get started:

The post A Beginner’s Guide for Contributing to Xamarin.Forms appeared first on Xamarin Blog.


Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.