Book Image

Xamarin Cross-Platform Development Cookbook

By : George Taskos
Book Image

Xamarin Cross-Platform Development Cookbook

By: George Taskos

Overview of this book

<p>You can create native mobile applications using the Xamarin Forms platform for the three major platforms iOS, Android, and Windows Phone. The advantage of this is sharing as much code as you can, such as the UI, business logic, data models, SQLite data access, HTTP data access, and file storage across the three major platforms.</p> <p>This book provide recipes on how to create an architecture that will be maintainable, extendable, use Xamarin Forms plugins to boost productivity, customize your views per platforms, and use platform-specific implementations at runtime.</p> <p>We start with a simple creation of a Xamarin Forms solution with the three major platforms. We will then jump to XAML recipes and you will learn how to create a tabbed application page, and customize the style and behavior of views for each platform. Moving on, you will acquire more advanced knowledge and techniques while implementing views and pages for each platform and also calling native UI screens such as the native camera page.</p> <p>Further on, we demonstrate the power of architecting a cross-platform solution and how to share code between platforms, create abstractions, and inject platform-specific implementations. Next, you will utilize and access hardware features that vary from platform to platform with cross-platform techniques. Well then show you the power of databinding offered by Xamarin Forms and how you can create bindable models and use them in XAML. You will learn how to handle user interactions with the device and take actions in particular events.</p> <p>With all the work done and your application ready, you will master the steps of getting the app ready and publishing it in the app store.</p>
Table of Contents (18 chapters)
Xamarin Cross-Platform Development Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Creating a cross-platform login screen


Almost every application has an authentication screen. Here, we will examine the root application page of a Xamarin.Forms application by creating a login screen where the user can set his username, password and tap the login button to get access.

You can create a new solution or continue from the previous section.

How to do it...

In our core PCL project:

  1. Open the FormsCookbook.cs file.

  2. Replace the code in the constructor with the following code snippet:

    var userNameEntry = new Entry {
      Placeholder = "username"
    };
    var passwordEntry = new Entry {
      Placeholder = "password",
      IsPassword = true
    };
    var loginButton = new Button {
      Text = "Login"
    };
    
    loginButton.Clicked += (sender, e) => {
      Debug.WriteLine(string.Format("Username: {0} - Password: {1}", userNameEntry.Text, passwordEntry.Text));
    };
    
    MainPage = new ContentPage {
      Content = new StackLayout {
        VerticalOptions = LayoutOptions.Center,
        Children = {
          userNameEntry,
          passwordEntry,
          loginButton
        }
      }
    };
  3. Run the application for each platform; you should get the two native default text input controls and a button.

  4. Set your username and password in the corresponding textboxes.

  5. Click the Login button and watch the application output printing the message we set up in the Clicked delegate event handler.

You should see something similar to the following screenshot:

In iOS:

In Android:

In Windows:

This is all great: the default layout looks OK and everything is aligned in the middle of the screen and to the edge of the screen. Of course, every view and layout container has properties that will align and add spacing between controls. Let's try to change things up a little bit. It's good to start organizing our code better too.

  1. Right-click in the core PCL project and Add | New Folder; name it Custom Pages.

  2. Right-click in the Custom Pages folder and Add | New File; choose Empty Class, set the name to MainPage, and click New.

  3. In the constructor of the new class, write or paste the following code:

    public class MainPage: ContentPage {
      Entry userNameEntry;
      Entry passwordEntry;
      Button loginButton;
      StackLayout stackLayout;
    
      public MainPage() {
        userNameEntry = new Entry {
          Placeholder = "username"
        };
        passwordEntry = new Entry {
          Placeholder = "password",
          IsPassword = true
        };
        loginButton = new Button {
          Text = "Login"
        };
    
        loginButton.Clicked += LoginButton_Clicked;
    
        this.Padding = new Thickness(20);
    
        stackLayout = new StackLayout {
          VerticalOptions = LayoutOptions.FillAndExpand,
          HorizontalOptions = LayoutOptions.FillAndExpand,
          Orientation = StackOrientation.Vertical,
          Spacing = 10,
          Children = {
          userNameEntry,
          passwordEntry,
          loginButton
          }
        };
    
        this.Content = stackLayout;
      }
    
      void LoginButton_Clicked(object sender, EventArgs e) {
        Debug.WriteLine(string.Format("Username: {0} - Password: {1}",
        userNameEntry.Text, passwordEntry.Text));
      }
    }
  4. Make the MainPage class a subclass of ContentPage.

    public class MainPage : ContentPage
  5. Replace the FormsCookbook.cs constructor with the following code:

    MainPage = new MainPage ();
  6. Run the application for each platform to see the results.

You should see something similar to the following screenshot:

In iOS:

In Android:

In Windows:

How it works…

FormsCookbook.cs is the main application entry that contains a MainPage property where we assign the application initial page.

For the Content of the MainPage we create a StackLayout, and for its children we add our three Views: userNameEntry, passwordEntry, and loginButton with VerticalOptions, HorizontalOptions, Orientation, Spacing.

We assigned a delegate handler for the Clicked event of the loginButton to respond to our finger tap. Nothing fancy here, just printing a message to the Application Output window.

The Xamarin.Forms UI hierarchy is based on a more adaptive layout; we don't specify positions with coordinates, but rather with layout containers, which we add child elements and specific rules.

To fine-tune our login screen, we used the StackLayout's container properties, VerticalOptions and HorizontalOptions, to determine how the child content is positioned, spacing for the space between the controls and padding for around the element.

Note

When it comes to width and height, there is no straightforward way to set these properties in Xamarin.Forms views. What we actually do is request the width and height, and with no guarantee that it will happen the layout will try to complete your request. The Width and Height are read-only properties.

There's more…

When it comes to a native cross-platform application like Xamarin.Forms, don't forget that we are running in different platforms, and different platforms have different screen sizes with different measurement systems: iOS units, Android and Windows Phone, device-independent pixels.

How does Xamarin.Forms deal with that? For example, if you say Spacing=10 then it will be 10 in the specific platform's measurement system, 10 units in iOS, and 10 dpi in Android and Windows Phone.