VISUAL STUDIO   Windows Mac

Using the Android Designer

PDF for offline use

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-08

This article is a walkthrough of the Xamarin.Android Designer. It demonstrates how to create a user interface for a small color browser app; this user interface is created entirely in the Designer.

Contents

Overview

Android user interfaces can be created declaratively by using XML files or programmatically by writing 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 evaluate UI changes without having to redeploy the application to a device or to an emulator. This can speed up Android UI development tremendously. In this article, we present a walkthrough that shows how to use the Xamarin.Android Designer to visually create a user interface.

Walkthrough

The objective of this walkthrough is to use the Android Designer to create a user interface for an example color browser app that presents a list of colors, their names, and their RGB values. We'll look at how to add widgets to the Design Surface as well as how to lay out these widgets visually. After that, we'll explain how to modify widgets interactively on the Design Surface or by using the Designer's Property Pad. Finally, we'll see how our design looks when we run the app.

Let's get started!

Creating a New Project

The first step is to create a new Xamarin.Android project.

Launch Visual Studio for Mac and click New Solution.... Choose the Android App template and click Next:

Android blank app

Launch Visual Studio and click New Project... then choose the Visual C# > Android > Blank App (Android) template:

Android blank app

Name the new app DesignerWalkthrough. Under Target Platforms, select Latest and Greatest and click Next:

Name app

In the next dialog screen, click Create.

Name the new app DesignerWalkthrough and click OK.

Name app

Adding a Layout

Let's create a LinearLayout that we will use to hold our user interface elements.

In Visual Studio for Mac, right-click Resources/layout in the Solution pad and select Add > New File.... In the New File dialog, select Android > Layout. Name the file ListItem and click New:

New layout

The new ListItem layout is displayed in the Designer:

Designer view

Click the Source tab at the bottom of the Designer to view the XML source for this layout. When you click the Document Outline tab on the right, it shows that the layout currently contains a single LinearLayout widget:

Designer XML

In Visual Studio, right-click Resources/layout in the Solution Explorer and select Add > New Item.... In the Add New Item dialog, select Android Layout. Name the file ListItem.axml and click Add:

New layout

The new ListItem layout is displayed in the Designer:

Designer view

Click the Source tab at the bottom of the Designer to view the XML source for this layout:

Designer XML

From the View menu, click Other Windows > Document Outline to open the Document Outline. The Document Outline shows that the layout currently contains a single LinearLayout widget:

Document outline

Creating the List Item User Interface

Next, we are going to create the user interface for the color browser app. Click the Designer tab to return to the Design Surface. In the Toolbox, scroll down to the Images & Media section and peruse each item until you locate an ImageView:

Locate ImageView

Locate ImageView

Alternately, you can enter ImageView into the search bar to locate the ImageView widget:

ImageView search

ImageView search

Drag this ImageView onto the Design Surface:

ImageView on canvas

ImageView on canvas

This ImageView will be used to display a color swatch in our color browser app.

Next, drag a LinearLayout (Vertical) widget from the Toolbox into the Designer. Note that a blue outline indicates the boundaries of the added LinearLayout, and the Document Outline shows that it resides directly below imageView1 (ImageView):

Blue outline

Blue outline

When you select the ImageView in the Designer, the blue outline moves to surround the ImageView; in the Document Outline, the selection moves to imageView1 (ImageView):

Select ImageView

Select ImageView

Next, drag a Text (Large) widget from the Toolbox into the newly-added LinearLayout. Notice that the Designer uses green highlights to indicate where the new widget will be inserted:

Green highlights

Green highlights

Next, add a Text (Small) widget below the Text (Large) widget:

Add small text widget

Add small text widget

At this point, the Designer should resemble the following screenshot:

Designer layout

Designer layout

If the two textView widgets are not inside linearLayout1, you can drag them to linearLayout1 in the Document Outline and position them so they appear as shown in the previous screenshot (indented under linearLayout1).

Arranging the User Interface

Let's modify the UI to display the ImageView on the left, with the two TextView widgets stacked to the right of the ImageView.

  1. With the ImageView selected, click the Properties tab.

  2. Just below the Properties tab, click Layout.

  3. Scroll down to ViewGroup and change the Width setting to wrap_content:

Set wrap content

  1. Select the ImageView.

  2. In the Properties window, click the Categorized sort icon and scroll down to the Layout - ViewGroup section.

  3. Change the layout_width setting to wrap_content:

Set wrap content

Another way to change the Width setting is to click the triangle on the right-hand side of the widget to toggle its width setting to wrap_content:

Drag to set width

Clicking the triangle again returns the Width setting to match_parent.

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

Select root LinearLayout

Select root LinearLayout

With the root LinearLayout selected, return to the Properties tab and click Widget. Change the Orientation setting to horizontal:

Select horizontal orientation

With the root LinearLayout selected, return to the Properties window, click the Alphabetical sort icon and scroll until you find orientation. Change the orientation setting to horizontal:

Select horizontal orientation

At this point, the Designer should resemble the following screenshot:

Designer layout

Designer layout

Modifying the Spacing

Next, we'll modify padding and margin settings in the UI to provide more space between the widgets. Select the ImageView and click the Layout tab under Properties. Change the Padding to 10dp, the Min Width to 50dp, and the Min Height to 70dp. This applies padding around all sides of the ImageView and elongates it vertically:

Set padding

Next, we'll modify padding and margin settings in the UI to provide more space between the widgets. Select the ImageView, click the Categorized search icon in the Properties window and scroll down to the Layout section. Change the Min Height to 70dp, the Min Width to 50dp, and the padding to 10dp. This applies padding around all sides of the ImageView and elongates it vertically:

Set padding

The top, right, bottom, and left padding settings can be set independently by entering values into the Top, Right, Bottom, and Left padding fields, respectively. For example, set the Left padding value to 5dp and the Top, Right, and Bottom padding values to 10dp. Note that the Padding setting changes to a comma-separated list of these values:

Custom padding settings

The bottom, left, right, and top padding settings can be set independently by entering values into the paddingBottom, paddingLeft, paddingRight, and paddingTop fields, respectively. For example, set the paddingLeft field to 5dp and the paddingBottom, paddingRight, and paddingTop fields to 10dp:

Custom padding settings

Next, tweak the position of the LinearLayout widget that contains the two TextView widgets. In the Document Outline, select linearLayout1. In the Properties pane, select the Layout tab. Scroll down to the ViewGroup section and set the Left, Top, Right, and Bottom margins to 5dp, 5dp, 0dp, and 5dp respectively:

Set margins

Next, tweak the position of the LinearLayout widget that contains the two TextView widgets. In the Document Outline, select linearLayout1. In the Properties window, scroll to the Layout - ViewGroup section. Set layout_marginBottom, layout_marginLeft, layout_marginRight, and layout_marginTop to 5dp, 5dp, 0dp, and 5dp respectively:

Set margins

Removing the Default Image

Because we're using the ImageView to display colors (rather than images), let's remove the default image source added by the template.

  1. Select the ImageView.

  2. Click the Widget tab under Properties.

  3. Clear the Src setting so that it is blank:

Clear the ImageView src setting

  1. Select the ImageView.

  2. In Properties, find the src field.

  3. Clear the src setting so that it is blank:

Clear the ImageView src setting

Adding a ListView Container

Now that the ListItem layout is defined, we'll add a ListView to the Main layout. This ListView will contain a list of ListItems. In the ToolBox, locate the ListView widget and drag it onto the Design Surface. The ListView in the Designer will be blank except for blue lines that outline its border when it is selected. You can view the Document Outline to verify that the ListView was added correctly:

New ListView

New ListView

By default, the ListView is given an Id value of @+id/listView1. Open the Widget tab under Properties and change the Id to @+id/myListView:

Rename id to myListView

Rename id to myListView

At this point, our user interface is ready to use.

Running the Application

Open MainActivity.cs and replace its code with the following:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;

namespace DesignerWalkthrough
{
    [Activity (Label = "DesignerWalkthrough", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        List<ColorItem> colorItems = new List<ColorItem> ();
        ListView listView;

        protected override void OnCreate (Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);

            SetContentView (Resource.Layout.Main);
            listView = FindViewById<ListView> (Resource.Id.myListView);

            colorItems.Add (new ColorItem () { Color = Android.Graphics.Color.DarkRed,
                                               ColorName = "Dark Red", Code = "8B0000" });
            colorItems.Add (new ColorItem () { Color = Android.Graphics.Color.SlateBlue,
                                               ColorName = "Slate Blue", Code = "6A5ACD" });
            colorItems.Add (new ColorItem () { Color = Android.Graphics.Color.ForestGreen,
                                               ColorName = "Forest Green", Code = "228B22" });

            listView.Adapter = new ColorAdapter (this, colorItems);
        }
    }
    public class ColorAdapter : BaseAdapter<ColorItem>
    {
        List<ColorItem> items;
        Activity context;
        public ColorAdapter(Activity context, List<ColorItem> items)
            : base()
        {
            this.context = context;
            this.items = items;
        }
        public override long GetItemId(int position)
        {
            return position;
        }
        public override ColorItem this[int position]
        {
            get { return items[position]; }
        }
        public override int Count
        {
            get { return items.Count; }
        }
        public override View GetView (int position, View convertView, ViewGroup parent)
        {
            var item = items[position];

            View view = convertView;
            if (view == null) // no view to re-use, create new
                view = context.LayoutInflater.Inflate(Resource.Layout.ListItem, null);
            view.FindViewById<TextView>(Resource.Id.textView1).Text = item.ColorName;
            view.FindViewById<TextView>(Resource.Id.textView2).Text = item.Code;
            view.FindViewById<ImageView>(Resource.Id.imageView1).SetBackgroundColor(item.Color);

            return view;
        }
    }

    public class ColorItem
    {
        public string ColorName { get; set; }
        public string Code { get; set; }
        public Android.Graphics.Color Color { get; set; }
    }
}

This code uses a custom ListView adapter to load color information and display this data in the UI we've just created. To keep this example short, the color information is hard-coded in a list, but the adapter could be modified to extract color information from a data source or to calculate it on the fly. For more information about ListView adapters, see ListViews and Adapters.

Build and run the application. The following screenshot is an example of how the app appears when running on a device:

Final screenshot

Summary

In this article, we walked through how to use the Xamarin.Android Designer in Visual Studio for Mac to create a user interface. Next, we demonstrated how to create the interface for a single item in a list. Along the way, we looked at how to add widgets and to lay them out visually, as well as how to assign resources and to set various properties on those widgets. In conclusion, we illustrated how the interface we created in the Designer runs in an example application.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.