Home > Sample chapters > Programming > Windows

Creating Mobile Apps with Xamarin.Forms: Infrastructure

This chapter from Creating Mobile Apps with Xamarin.Forms, Preview Edition presents an actual application built from the ground up.

Sometimes programming tutorials such as this one can cover a lot of ground before directly addressing the needs of real-world applications. This chapter and the next are an attempt to avoid that common problem.

These two chapters present an actual application built from the ground up. This won’t be a very sophisticated application, but it will be usable and useful. The application’s name is NoteTaker, and it lets you take notes and save them.

Each note is some text—as much text as you want—and an optional title. If you don’t specify a title, one will be generated for you from the first few words of the note.

When the program is finally finished at the end of the next chapter, it will have the following home screen:

That’s a scrollable lists of the titles of the notes you’ve already created. A New button symbolized by a plus sign appears as a toolbar item either at the top or bottom of the screen. Tap that button and the program navigates to a page for entering a new note:

You can also edit an existing note by tapping that note on the home screen:

Toolbar items allow you to cancel the editing or delete the note. The New Note and Edit Note screens are very similar, so it’s probably not surprising that they are simply variations of the same page.

Engineering in general is a problem-solving activity, and programming is no different. We begin with a vision and then plan a strategy and set some goals to begin realizing that vision in code. But in attempting to build the program, problems and obstacles are often encountered. It is in solving these problems that we battle through our ignorance to acquire knowledge and skills.

In this chapter the NoteTaker program goes through six different versions. They are numbered 1 through 6, but the version numbers should probably be more like 0.1 through 0.6. In the course of enhancing this program through these six versions, the following topics are encountered:

  • The Entry and Editor views for editing text
  • File input/output (I/O) in the mobile environment
  • Asynchronous operations
  • Property change notifications
  • Data binding

The next chapter gets into multi-page architectures, page navigation, the powerful ListView for displaying collections of items, and dealing with application lifecycle issues.

Version 1. The Entry and Editor views

The NoteTaker app definitely requires some text input. Some phones have physical keyboards, but the vast majority are limited to virtual onscreen keyboards. Of course, these are somewhat different for each platform and often also vary by the type of text input.

Xamarin.Forms defines two views for obtaining text input:

  • Entry for a single line of text
  • Editor for multiple lines of text

Both Entry and Editor derive from InputView, which derives from View.

All three platforms have various styles of virtual keyboard appropriate for different types of text input. For example, a keyboard for typing a URL should be different from a keyboard for entering a phone number. For this reason, InputView defines a property named Keyboard of type Keyboard, a class that defines seven static read-only properties of type Keyboard appropriate for different keyboard uses:

  • Default
  • Text
  • Chat
  • Url
  • Email
  • Numeric
  • Telephone

For example, if you have an Entry view intended for entering a URL, specify:

entry.Keyboard = Keyboard.Url;

Of course, the actual keyboards are platform-specific, and not all three platforms have distinct keyboards for all seven static properties.

The Keyboard class an alternative way to specify a keyboard using a KeyboardFlags enumeration, which has the following flag members:

  • CapitalizeSentence (equal to 1)
  • Spellcheck (2)
  • Suggestions (4)
  • All (\xFFFFFFFF)

These flags make more sense with an Editor rather than an Entry because the user is likely to be typing real text consisting of actual words organized into sentences. Set the keyboard like this:

editor.Keyboard = Keyboard.Create(KeyboardFlags.All);

The phone’s operating system displays the virtual keyboard when the Entry or Editor acquires keyboard input focus. Input focus means that keyboard input is directed towards that particular view. Only one view can have input focus at any time. Although any Xamarin.Forms view can get input focus, only Entry and Editor are equipped to process that input.

A view must have its IsEnabled property set to true (the default state) to acquire input focus. A user can give an enabled view input focus by tapping it. When the Entry or Editor acquires input focus, the operating system pops up the keyboard.

A user can remove keyboard focus from an Entry or Editor by tapping somewhere else on the screen. The keyboard is automatically dismissed. But this is not the only way to dismiss the keyboard. Often a specific keyboard key or button associated with the keyboard lets the user signal that text input is complete. The concept of signaling that text is complete is complicated somewhat by the different nature of the Entry and Editor views: An Enter or Return key often removes input focus from an Entry view, but in an Editor that same key instead simply marks the end of one paragraph and the beginning of another.

On the iPhone, a Return button dismisses the keyboard from an Entry and a special Done button dismisses the keyboard from an Editor. On the Android, a Done key dismisses the keyboard from the Entry but a button on the bottom of the screen is required to dismiss the keyboard from the Editor. On the Windows Phone, the Enter key dismisses the keyboard from the Entry but the hardware Back button dismisses the keyboard from the Editor.

The Entry and Editor define Focused and Unfocused events that signal gaining and losing input focus. The IsFocused property indicates if a particular view currently has input focus. A program can attempt to set focus to a particular view in code by calling the Focus method on the view. The method returns true if the focus change was successful. These focus-related members are defined by Visual-Element, the base class for all UI elements, but they are really only relevant for the Entry and Editor.

Both Entry and Editor define Text properties that expose the current text displayed by the view. A program can initialize this Text property and then allow the user to edit that text.

Both Entry and Editor define a Completed event that is fired when the user has signaled that editing is completed. This is an excellent opportunity for programs to access the Text property and save the results.

Both Entry and Editor also define a TextChanged event that is fired when the Text property changes. (Keep in mind that .NET string objects are immutable. A string object can’t itself change after it’s been created. Every time the contents of the Entry or Editor change, it’s a whole new string object rather than a modified string object.) The TextChanged event can be a valuable means for the application to monitor the text input on a character-by-character basis and respond to changes before the user signals that the typing is complete.

You might assume that Entry is somewhat simpler than Editor because it handles only a single line of text. However, Entry has three additional properties that Editor doesn’t have:

  • TextColor — a Color value
  • IsPassword — a Boolean that causes characters to be masked
  • Placeholder — light colored text that appears in the Entry but disappears as soon as the user begins typing.

The NoteTaker program requires a page that contains an Entry for the user to type a title for the note, and an Editor for typing the note itself. For the first version of this program—called NoteTaker1—let’s not do much more beyond getting these two views on the page with a couple of Label views for identification.

The Editor allows an indefinite amount of text to be entered and internally implements scrolling. As you discovered with the ScrollView in the previous chapter, sharing a scrollable view with other views on the page requires that the VerticalOptions property be set to LayoutOptions.-FillAndExpand.

Here’s the NoteTaker1Page class:

class NoteTaker1Page : ContentPage{        
   public NoteTaker1Page()
   {
       this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 0);
       this.Content = new StackLayout
       {
           Children =
           {
               new Label
               {
                   Text = "Title:"
               },
               new Entry
               {
                   Placeholder = "Title (optional)"
               },
               new Label
               {
                   Text = "Note:"
               },
               new Editor
               {
                   Keyboard = Keyboard.Create(KeyboardFlags.All),
                   BackgroundColor = Device.OnPlatform(Color.Default,
                                                       Color.Default,
                                                       Color.White),
                   VerticalOptions = LayoutOptions.FillAndExpand
               },
               new Button
               {
                   Text = "Save",
                   HorizontalOptions = LayoutOptions.Center
               }
           }
       };
   }
}

The program explicitly sets the BackgroundColor property on the Editor to correct a little flaw in the Windows Phone implementation: Without this setting, the Editor background goes black when it loses input focus, and that causes the black text to be invisible.

Here’s what it looks like with some text typed in:

The Button at the bottom labeled Save currently does nothing. Such a button is undoubtedly intended to save the note to a file. To do that, however, we need to know how to save files, and later load them back in.

File input/output is not something included in the Xamarin.Forms API. Yet, some file I/O is required by many mobile apps, if only to save settings and interim data. For this reason, file I/O is probably the most compelling reason to skirt around the Xamarin.Forms API and implement some vital features of your app by using the programming interfaces of the individual platforms.