Cross Platform
Android
iOS
Mac
Test Cloud

Walkthrough - Using the Android Designer

This article presents a walkthrough of the Xamarin.Android designer. It shows how to create a list-based user interface that will be used to present contacts, including the thumbnail images, names, and phone numbers of those contacts. This user interface will be created entirely in the designer.

Overview

Android user interfaces can be created declaratively by using XML files, or programmatically in code. The Xamarin Android Designer allows developers to create and modify declarative layouts visually, without having to deal with the tedium of hand-editing XML files. The designer also provides real-time feedback, which lets the developer validate changes without having to redeploy the application in order to test a design. This can speed up UI development in Android tremendously.

In this article, we will present a walkthrough that shows how to use the Xamarin.Android designer to visually create a user interface. We’ll create a user interface that will present a list of contacts, and then we’ll look at how to add controls to the designer surface, as well as how to lay out these controls visually. After that, we’ll explain how to assign an image resource, and then we’ll describe two ways to modify controls: interactively on the designer surface, or by using the designer’s Property Pad.

Let’s get started. The first step is to create a new project.

Creating a New Project

  1. Launch Xamarin Studio, and then create a new Android solution called DesignerWalkthrough:

Adding a Layout

The first thing we need to do is add a layout.

  1. Right-click on Resources/layout in the Solution pad, and then select Add New File.

  2. In the New File dialog, select Mono for Android and Android Layout, naming the file ListItem:

  3. Click New to create the layout file and load it in the designer:

This creates an Android XML file with a single LinearLayout, as seen in the DocumentOutline:

At the bottom of the designer, there is a tab titled Source that allows switching to XML view, where we can see that the LinearLayout element was added:

Creating the List Item User Interface

  1. Switch back to Content view now where we will edit the user interface.

We are going to create the user interface for a contact here.

  1. First, add an image named Placeholder.png to the project under Resources/drawable. We’ll use this placeholder image for the contact. An image is included in the project that accompanies this tutorial.

  2. In the Toolbox, scroll down to the Images & Media section, and then drag an ImageView onto the designer:

  3. Next, drag a LinearLayout (Vertical) from the Layouts section in the Toolbox to the designer surface, and then drop it below the ImageView. Notice the dotted lines showing the layout’s bounds:

If we select the layout control on the designer surface, the blue border denoting the currently selected control switches from the ImageView to the layout. Also, notice how the Document Outline stays in sync with the current selection. The inverse is also true. We could select the control from the outline and the designer would reflect the selection:

  1. Next, drag a Text (Large) widget from the Form Widgets section of the Toolbox to the LinearLayout we added above. Notice how the designer displays green lines to denote where the control will be inserted:

  2. Add a Text (Small) widget below the Text (Large).

The designer at this point should look like the screenshot below:

Layout the UI

Let’s modify the UI now to display the ImageView on the left, with the two TextViews just to the right of the ImageView.

  1. With the ImageView selected, switch to the Properties tab, located just below the DocumentOutline.

  2. Under Properties, select the Layout tab at the top.

  3. Under the LinearLayout section, change the Width to wrap_content:

Alternatively, with the ImageView selected, you could also click the arrow on the left side of the control to change the layoutwidth. The top arrow, pointing left, changes the value to wrapcontent:

  1. Next, switch to the Document Outline, and then select the root LinearLayout:

  2. With the LinearLayout selected, go back to the Properties, and then choose the Widget tab. Set the Orientation to horizontal:

At this point, the designer should look like the screenshot below:

Assigning the Image from a Resource

Let’s assign the image we added earlier to the ImageView.

  1. Select the ImageView in the designer, and then select the Widget tab under Properties.

  2. Set the Src to @drawable/Placeholder .

Now the designer shows a preview of the image:

Modifying the Spacing

Let’s space things out a bit.

  1. With the ImageView still selected, select the Layout tab under Properties, and then set the Padding to 10dp. This will apply padding to the top, left, bottom, and right of the ImageView:

We could also click the ellipsis next to the Padding to set each value independently.

  1. For example, set the Top and Left to 5dp, and the Bottom and Right to 10dp. Also set the Height of the ImageView to 50dp to match the actual height of the placeholder image:

  2. Switch to the Widget tab, and then check the box next to Adjust View Bounds:

Next, let’s tweak the position of the LinearLayout that contains the two TextView controls.

  1. Select the LinearLayout in the Document Outline, and then select the Layout tab under Properties. Set the Left, Top, Right, and Bottom margins to 0, 5, 5, and 0dp, respectively.

The designer reflects these changes as shown below:

Adding a ListView

With the ListItem in place, now we will add a ListView to contain the ListItems.

  1. Switch to the Main.axml file by double-clicking it in the Solution Pad, which loads it into the designer.

The file consists of a LinearLayout that contains a button, which was added by the default project template.

  1. Delete the button from the designer. Go to the Activity1 class, and then remove the button code added by the template in the OnCreate method.

  2. In the Toolbox, scroll to the Composite sections, and then drag a ListView onto the designer. The ListView on the designer will be blank, only showing the blue lines of its border when selected. However, we can verify that it was added correctly in the Document Outline:

By default, the ListView control is given the Id ListView1. We can change this Id in the Widget tab under Properties.

  1. For example, change the Id to contactsListView:

The user interface for displaying a list of items with images is now ready to use.

Running the Application

For this example, we’ll use contact data to populate the user interface. To do this, we must add the READ_CONTACTS permission to the AndroidManifest. For instructions on how to add permissions to the AndroidManifest, see Working with AndroidManifest.xml.

The code uses a custom adapter, shown below, to load the contacts and display their data in the UI we just created. See the project that accompanies this article for more details.

public class ContactsAdapter : BaseAdapter
{
List<Contact> _contactList;
Activity _activity;

public ContactsAdapter (Activity activity)
{
    _activity = activity;
    FillContacts ();
}

public override int Count {
    get { return _contactList.Count; }
}

public override Java.Lang.Object GetItem (int position)
{
    return null;
}

public override long GetItemId (int position)
{
    return _contactList [position].Id;
}

public override View GetView (int position,
View convertView, ViewGroup parent)
{          
    var view = convertView ?? _activity.LayoutInflater.Inflate
    (Resource.Layout.ListItem, parent, false);
    var contactName =
    view.FindViewById<TextView> (Resource.Id.textView1);
    var textView2 =
    view.FindViewById<TextView>
    (Resource.Id.textView2);
    var contactImage =
    view.FindViewById<ImageView>
    (Resource.Id.imageView1);
    textView2.Text = _contactList [position].Number;
    contactName.Text = _contactList [position].DisplayName;
           if (_contactList [position].PhotoId == null) {
                contactImage = view.FindViewById<ImageView>
                    (Resource.Id.imageView1);
                contactImage.SetImageResource
                    (Resource.Drawable.Placeholder);
            } else {
                var contactUri = ContentUris.WithAppendedId
                    (ContactsContract.Contacts.ContentUri,
                    _contactList [position].Id);
                var contactPhotoUri =
                    Android.Net.Uri.WithAppendedPath(
                    contactUri,
                    ContactsContract.Contacts
                    .Photo.ContentDirectory);
                contactImage.SetImageURI (contactPhotoUri);
            }
    return view;
}

void FillContacts ()
{
    var uri = ContactsContract.Contacts.ContentUri;
    string[] projection = {
        ContactsContract.Contacts.InterfaceConsts.Id,
        ContactsContract.Contacts.InterfaceConsts
            .DisplayName,
        ContactsContract.Contacts.InterfaceConsts.PhotoId
      };
    var cursor = _activity.ManagedQuery (uri,
            projection,null, null, null);
           _contactList = new List<Contact> ();  
     if (cursor.MoveToFirst ()) {
        do {
            _contactList.Add (new Contact{
                      Id = cursor.GetLong (
                           cursor.GetColumnIndex (
                               projection [0])),
                       DisplayName =
                           cursor.GetString (
                               cursor.GetColumnIndex (
                               projection [1])),
                       PhotoId =
                               cursor.GetString (
                                   cursor.GetColumnIndex (
                                   projection [2])),
                       Number = "(123) 456 - 7890"
             });
        } while (cursor.MoveToNext());
     }
}

class Contact
{
    public long Id { get; set; }
    public string DisplayName{ get; set; }
    public string PhotoId { get; set; }
    public string Number { get; set; }
}
}

The ContactAdapter is assigned to the Adapter property of the ListView in the OnCreate method of the Activity:

var contactsAdapter = new ContactsAdapter (this);
var contactsListView =
FindViewById<ListView> (Resource.Id.contactsListView);
contactsListView.Adapter = contactsAdapter;

The following screenshot shows the application running on a device:

Summary

In this article, we walked through how to use the Xamarin.Android designer in Xamarin Studio to create a user interface. Then, we showed how to create the interface for a single item in a list. Along the way, we looked at how to add controls and lay them out visually, as well as how to assign resources and set various properties on those controls. In conclusion, we showed how the interface we created in the designer runs in an application that displays contacts.

Part 1 - Designer Basics >>