27 min read

In this article by Nilanchala Panigrahy, author of the book Xamarin Mobile Application Development for Android Second Edition, will walk you through the activities related to creating and populating a ListView, which includes the following topics:

  • Creating the POIApp activity layout
  • Creating a custom list row item layout
  • The ListView and ListAdapter classes

(For more resources related to this topic, see here.)

It is technically “possible to create and attach the user interface elements to your activity using C# code. However, it is a bit of a mess. We will go with the most common approach by declaring the XML-based layout.

Rather than deleting these files, let’s give them more appropriate names and remove unnecessary content as follows:

  1. Select the Main.axml file in Resources | Layout and rename it to “POIList.axml.
  2. Double-click on the POIList.axml file to open it in a layout “designer window.Currently, the POIList.axml file contains the layout that was created as part of the default Xamarin Studio template. As per our requirement, we need to add a ListView widget that takes the complete screen width and a ProgressBar in the middle of the screen. The indeterminate progress “bar will be displayed to the user while the data is being downloaded “from the server. Once the download is complete and the data is ready, “the indeterminate progress bar will be hidden before the POI data is rendered on the list view.
  3. Now, open the “Document Outline tab in the designer window and delete both the button and LinearLayout.
  4. Now, in the designer Toolbox, search for RelativeLayout and drag it onto the designer layout preview window.
  5. Search for ListView in the Toolbox search field and drag it over the layout designer preview window. Alternatively, you can drag and drop it over RelativeLayout in the Document Outline tab.

We have just added a ListView widget to POIList.axml. Let’s now open the Properties pad view in the designer window and edit some of its attributes:

There are five buttons at the top of the pad that switch the set of properties being edited. The @+id notation notifies the compiler that a new resource ID needs to be created to identify the widget in API calls, and listView1 identifies the name of the constant. Now, perform the following steps:

  1. Change the ID name to poiListView and save the changes. Switch back to the Document Outline pad and notice that the ListView ID is updated.
  2. Again, switch back to the Properties pad and click on the Layout button.
  3. Under the View Group section of the layout properties, set both the Width and Height properties to match_parent.
  4. The match_parent value “for the Height and Width properties tells us that the ListView can use the entire content area provided by the parent, excluding any margins specified. In our case, the parent would be the top-level RelativeLayout.

    Prior to API level 8, fill_parent was used instead of match_parent to accomplish the same effect. In API level 8, fill_parent was deprecated and replaced with match_parent for clarity. Currently, both the constants are defined as the same value, so they have exactly the same effect. However, fill_ parent may be removed from the future releases of the API; so, going forward, match_parent should be used.

    So far, we have added a ListView to RelativeLayout, let’s now add a Progress Bar to the center of the screen.

  5. Search for Progress Bar in the Toolbox search field. You will notice that several types of progress bars will be listed, including horizontal, large, normal, and small. Drag the normal progress bar onto RelativeLayout.By default, the Progress Bar widget is aligned to the top left of its parent layout. To align it to the center of the screen, select the progress bar in the Document Outline tab, switch to the Properties view, and click on the Layout tab. Now select the Center In Parent checkbox, and you will notice that the progress bar is aligned to the center of the screen and will appear at the top of the list view.
  6. Currently, the progress bar is visible in the center of the screen. By default, this could be hidden in the layout and will be made visible only while the data is being downloaded.
  7. Change the Progress Bar ID to progressBar and save the changes.
  8. To hide the Progress Bar from the layout, click on the Behavior tab in the Properties view. From Visibility, select Box, and then select gone.This behavior can also be controlled by calling setVisibility() on any view by passing any of the following behaviors.

The View.Visibility property” allows you to control whether a view is visible or not. It is based on the ViewStates enum, which defines the following values:

Value Description
Gone This value tells the parent ViewGroup to treat the View as though it does not exist, so no space will be allocated in the layout
Invisible This value tells the parent ViewGroup to hide the content for the View; however, it occupies the layout space
Visible This value tells the parent ViewGroup to display the content of the View

Click on the Source tab to switch the IDE context from visual designer to code, and see what we have built so far. Notice that the following code is generated for the POIList.axml layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
   p1_layout_width="match_parent"
   p1_layout_height="match_parent"
   p1_id="@+id/relativeLayout1">
   <ListView
       p1_minWidth="25px"
       p1_minHeight="25px"
       p1_layout_width="match_parent"
       p1_layout_height="match_parent"
       p1_id="@+id/poiListView" />
   <ProgressBar
       p1_layout_width="wrap_content"
       p1_layout_height="wrap_content"
       p1_id="@+id/progressBar"
       p1_layout_centerInParent="true"
       p1_visibility="gone" />
</RelativeLayout>

Creating POIListActivity

When we created the” POIApp solution, along with the default layout, a default activity (MainActivity.cs) was created. Let’s rename the MainActivity.cs file “to POIListActivity.cs:

  1. Select the MainActivity.cs file from Solution Explorer and rename to POIListActivity.cs.
  2. Open the POIListActivity.cs file in the code editor and rename the “class to POIListActivity.
  3. The POIListActivity class currently contains the code that was “created automatically while creating the solution using Xamarin Studio. We will write our own activity code, so let’s remove all the code from the POIListActivity class.
  4. Override the OnCreate() activity life cycle callback method. This method will be used to attach the activity layout, instantiate the views, and write other activity initialization logic. Add the following code blocks to the POIListActivity class:
    namespace POIApp
    {
    [Activity (Label = "POIApp", MainLauncher = true, Icon = "@
    drawable/icon")]
    public class POIListActivity : Activity
    {
    protected override void OnCreate (Bundle savedInstanceState)
    {
       base.OnCreate (savedInstanceState);
    }
    }
    }
  5. Now let’s set the activity content layout by calling the SetContentView(layoutId) method. This method places the layout content directly into the activity’s view hierarchy. Let’s provide the reference to the POIList layout created in previous steps.
    At this point, the POIListActivity class looks as follows:

    namespace POIApp
    {
    [Activity (Label = "POIApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class POIListActivity : Activity
    {
       protected override void OnCreate (Bundle savedInstanceState)
       {
         base.OnCreate (savedInstanceState);
         SetContentView (Resource.Layout.POIList);
       }
    }
    }

Notice that in the preceding code snippet, the POIListActivity class uses some of the [Activity] attributes such as Label, MainLauncher, and Icon. During the build process, Xamarin.Android uses these attributes to create an entry in the AndroidManifest.xml file. Xamarin makes it easier by allowing all of the Manifest properties to set using attributes so that you never have to modify them manually in AndroidManifest.xml.

So far, we have “declared an activity and attached the layout to it. At this point, if you run the app on your Android device or emulator, you will notice that a blank screen will be displayed.

Creating the POI list row layout

We now turn our attention to the” layout for each row in the ListView widget. “The” Android platform provides a number of default layouts out of the box that “can be used with a ListView widget:

Layout Description
SimpleListItem1 A “single line with a single caption field
SimpleListItem2 A “two-line layout with a larger font and a brighter text color for the first field
TwoLineListItem A “two-line layout with an equal sized font for both lines and a brighter text color for the first line
ActivityListItem A “single line of text with an image view

All of the preceding three layouts provide a pretty standard design, but for more control over content layout, a custom layout can also be created, which is what is needed for poiListView.

To create a new layout, perform the following steps:

  1. In the Solution pad, navigate to Resources | Layout, right-click on it, and navigate to Add | New File.
  2. Select Android from the list on the left-hand side, Android Layout from the template list, enter POIListItem in the name column, and click on New.

Before we proceed to lay out the design for each of the row items in the list, we must draw on a piece of paper and analyze how the UI will look like. In our example, the POI data will be organized as follows:

There are a “number of ways to achieve this layout, but we will use RelativeLayout to achieve the same result. There is a lot going on in this diagram. Let’s break it down as follows:

  • A RelativeLayout view group is used as the top-level container; it provides a number of flexible options for positioning relative content, its edges, or other content.
  • An ImageView widget is used to display a photo of the POI, and it is anchored to the left-hand side of the RelativeLayout utility.
  • Two TextView widgets are used to display the POI name and address information. They need to be anchored to the right-hand side of the ImageView widget and centered within the parent RelativeLayout “utility. The easiest way to accomplish this is to place both the TextView classes inside another layout; in this case, a LinearLayout widget with “the orientation set to vertical.
  • An additional TextView widget is used to display the distance, and it is anchored on the right-hand side of the RelativeLayout view group and centered vertically.

Now, our task is to get this definition into POIListItem.axml. The next few sections describe how to “accomplish this using the Content view of the designer when feasible and the Source view when required.

Adding a RelativeLayout view group

The RelativeLayout layout “manager allows its child views to be positioned relative to each other or relative to the container or another container. In our case, for building the row layout, as shown in the preceding diagram, we can use RelativeLayout as a top-level view group. When the POIListItem.axml layout file was created, by default a top-level LinearLayout was added. First, we need to change the top-level ViewGroup to RelativeLayout. The following section will take you through the steps to complete the layout design for the POI list row:

  1. With POIListItem.axml opened in the content mode, select the entire layout by clicking on the content area. You should see a blue outline going around the edge. Press Delete. The LinearLayout view group will be deleted, and you will see a message indicating that the layout is empty.
  2. Alternatively, you can also select the LinearLayout view group from the Document Outline tab and press Delete.
  3. Locate the RelativeLayout view group in the toolbox and drag it onto the layout.
  4. Select the RelativeLayout view group from Document Outline. Open the Properties pad and change the following properties:
    • The Padding option to 5dp
    • The Layout Height option to wrap_content
    • The Layout Width option to match_parent

    The padding property controls how much space will be placed around each item as a margin, and the height determines the height of each list row. Setting the Layout Width option to match_ parent will cause the POIListItem content to consume the entire width of the screen, while setting the Layout Height option to wrap_content will cause each row to be equal to the longest control.

  5. Switch to the Code view to see what has been added to the layout. Notice that the following lines of code have been added to RelativeLayout:
    <RelativeLayout 
       p1_minWidth="25px"
       p1_minHeight="25px"
       p1_layout_width="match_parent"
       p1_layout_height="wrap_content"
       p1_id="@+id/relativeLayout1"
       p1_padding="5dp"/>

    Android runs on a “variety of devices that offer different screen sizes and densities. When specifying dimensions, you can use a number of different units, including pixels (px), inches (in), and density-independent pixels (dp). Density-independent pixels are abstract units based on 1 dp being 1 pixel on a 160 dpi screen. At runtime, Android will scale the actual size up or down based on the actual screen density. It is a best practice to specify dimensions using density-independent pixels.

Adding an ImageView widget

The ImageView widget in “Android is used to display the arbitrary image for different sources. In our case, we will download the images from the server and display them in the list. Let’s add an ImageView widget to the left-hand side of the layout and set the following configurations:

  1. Locate the ImageView widget in the toolbox and drag it onto RelativeLayout.
  2. With the ImageView widget selected, use the Properties pad to set the ID to poiImageView.
  3. Now, click on the Layout tab in the Properties pad and set the Height and Width values to 65 dp.
  4. In the property grouping named RelativeLayout, set Center Vertical to true. Simply clicking on the checkbox does not seem to work, but you can click on the small icon that looks like an edit box, which is to the right-hand side, and just enter true. If everything else fails, just switch to the Source view and enter the following code:
    p1:layout_centerVertical="true"
  5. In the property grouping named ViewGroup, set the Margin Right to 5dp. This brings some space between the POI image and the POI name.
  6. Switch to the Code view to see what has been added to the layout. Notice the following lines of code added to ImageView:
    <ImageView
           p1_src="@android:drawable/ic_menu_gallery"
           p1_layout_width="65dp"
           p1_layout_height="65dp"
    p1_layout_marginRight="5dp"
           p1_id="@+id/poiImageView" />

Adding a LinearLayout widget

LinearLayout is one of the “most basic layout managers that organizes its child “views either horizontally or vertically based on the value of its orientation property. Let’s add a LinearLayout view group that will be used to lay out “the POI name and address data as follows:

  1. Locate the LinearLayout (vertical) view group in the toolbox.
  2. Adding this widget is a little trickier because we want it anchored to the right-hand side of the ImageView widget.
  3. Drag the LinearLayout view group to the right-hand side of the ImageView widget until the edge turns to a blue dashed line, and then drop the LinearLayout view group. It will be aligned with the right-hand side of the ImageView widget.
  4. In the property grouping named RelativeLayout of the Layout section, set Center Vertical to true. As before, you will need to enter true in the edit box or manually add it to the Source view.
  5. Switch to the Code view to see what has been added to the layout. Notice “the following lines of code added to LinearLayout:
    <LinearLayout
           p1_orientation="vertical"
           p1_minWidth="25px"
           p1_minHeight="25px"
           p1_layout_width="wrap_content"
           p1_layout_height="wrap_content"
           p1_layout_toRightOf="@id/poiImageView"
           p1_id="@+id/linearLayout1"
           p1_layout_centerVertical="true" />

Adding the name and address TextView classes

Add the TextView classes to display the POI name and address:

  1. Locate TextView in” the Toolbox and add a TextView class to the layout. “This TextView needs to be added within the LinearLayout view group we just added, so drag TextView over the LinearLayout view group until it turns blue and then drop it.
  2. Name the TextView ID as nameTextView and set the text size to 20sp. “The text size can be set in the Style section of the Properties pad; you will need to expand the Text Appearance group by clicking on the ellipsis () button on the right-hand side.

    Scale-independent pixels (sp) “are like dp units, but they are also scaled by the user’s font size preference. Android allows users to select a font size in the Accessibility section of Settings. When font sizes are specified using sp, Android will not only take into account the screen density when scaling text, but will also consider the user’s accessibility settings. It is recommended that you specify font sizes using sp.

  3. Add “another TextView to the LinearLayout view group using the same technique except dragging the new widget to the bottom edge of the nameTextView until it changes to a blue dashed line and then drop it. This will cause the second TextView to be added below nameTextView. Set the font size to 14sp.
  4. Change the ID of the newly added TextView to addrTextView.
  5. Now change the sample text for both nameTextView and addrTextView to POI Name and City, State, Postal Code.
  6. To edit the text shown in TextView, just double tap the widget on the content panel. This enables a small editor that allows you to enter the text directly. Alternately, you can change the text by entering a value for the Text property in the Widget section of the Properties pad.
  7. It is a design practice to declare all your static strings in the Resources/values/string.xml file. By declaring the strings in the strings.xml file, you can easily translate your whole app to support other languages. Let’s add the following strings to string.xml:
    <string name="poi_name_hint">POI Name</string>
    <string name="address_hint">City, State, Postal Code.</string>
  8. You can now change the Text property of both nameTextView and addrTextView by selecting the ellipsis () button, which is next to the Text property in the Widget section of the Properties pad. Notice that this will open a dialog window that lists all the strings declared in the string.xml file. Select the appropriate strings for both TextView objects.
  9. Now let’s switch to the Code view to see what has been added to the layout. Notice the following lines of code added inside LinearLayout:
    <TextView
    p1_layout_width="match_parent"
    p1_layout_height="wrap_content"
    p1_id="@+id/nameTextView "
    p1_textSize="20sp"
    p1_text="@string/app_name" />
    <TextView
    p1_text="@string/address_hint"
    p1_layout_width="match_parent"
    p1_layout_height="wrap_content"
    p1_id="@+id/addrTextView "
    p1_textSize="14sp" />

Adding the distance TextView

Add a TextView to show “the distance from POI:

  1. Locate the TextView in the toolbox and add a TextView to the layout. This TextView needs to be anchored to the right-hand side of the RelativeLayout view group, but there is no way to visually accomplish this; so, we will use a multistep process. Initially, align the TextView with the right-hand edge of the LinearLayout view group by dragging it to the left-hand side until the edge changes to a dashed blue line and drop it.
  2. In the Widget section of the Properties pad, name the widget as distanceTextView and set the font size to 14sp.
  3. In the Layout section of the Properties pad, set Align Parent Right to true, Center Vertical to true, and clear out the linearLayout1 view group name in the To Right Of layout property.
  4. Change the sample text to 204 miles. To do this, let’s add a new string entry to string.xml and set the Text property from the Properties pad.The following screenshot depicts what should be seen from the Content view “at this point:

    Switch back to the “Source tab in the layout designer, and notice the following code generated for the POIListItem.axml layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
       p1_minWidth="25px"
       p1_minHeight="25px"
       p1_layout_width="match_parent"
       p1_layout_height="wrap_content"
       p1_id="@+id/relativeLayout1"
       p1_padding="5dp">
       <ImageView
           p1_src="@android:drawable/ic_menu_gallery"
           p1_layout_width="65dp"
           p1_layout_height="65dp"
    p1_layout_marginRight="5dp"
           p1_id="@+id/poiImageView" />
       <LinearLayout
           p1_orientation="vertical"
           p1_layout_width="wrap_content"
           p1_layout_height="wrap_content"
           p1_layout_toRightOf="@id/poiImageView"
           p1_id="@+id/linearLayout1"
           p1_layout_centerVertical="true">
           <TextView
               p1_layout_width="match_parent"
               p1_layout_height="wrap_content"
               p1_id="@+id/nameTextView "
               p1_textSize="20sp"
               p1_text="@string/app_name" />
           <TextView
               p1_text="@string/address_hint"
               p1_layout_width="match_parent"
               p1_layout_height="wrap_content"
               p1_id="@+id/addrTextView "
               p1_textSize="14sp" />
       </LinearLayout>
       <TextView
           p1_text="@string/distance_hint"
           p1_layout_width="wrap_content"
           p1_layout_height="wrap_content"
           p1_id="@+id/textView1"
           p1_layout_centerVertical="true"
           p1_layout_alignParentRight="true" />
    </RelativeLayout>

Creating the PointOfInterest apps entity class

The first class that is needed is the one that represents the primary focus of the application, a PointofInterest class. POIApp will allow the following attributes “to be captured for the Point Of Interest app:

  • Id
  • Name
  • Description
  • Address
  • Latitude
  • Longitude
  • Image

The POI entity class can be nothing more than a simple .NET class, which houses these attributes.

To create a POI entity class, perform the following steps:

  1. Select the POIApp project from the Solution Explorer in Xamarin Studio. Select the POIApp project and not the solution, which is the top-level node in the Solution pad.
  2. Right-click on it and select New File.
  3. On the left-hand side of the New File dialog box, select General.
  4. At the top of the template list, in the middle of the dialog box, select Empty Class (C#).
  5. Enter the name PointOfInterest and click on OK. The class will be created in the POIApp project folder.
  6. Change the “visibility of the class to public and fill in the attributes based on the list previously identified.

The following code snippet is from POIAppPOIAppPointOfInterest.cs from the code bundle available for this article:

public class PointOfInterest
   {
     public int Id { get; set;}
     public string Name { get; set; }
     public string Description { get; set; }
     public string Address { get; set; }
     public string Image { get; set; }
     public double? Latitude { get; set; }
     public double? Longitude { get; set; }
}

Note that the Latitude and Longitude attributes are all marked as nullable. In the case of latitude and longitude, (0, 0) is actually a valid location so a null value indicates that the attributes have never been set.

Populating the ListView item

All the adapter “views such as ListView and GridView use an Adapter that acts as a bridge between the data and views. The Adapter iterates through the content and generates Views for each data item in the list.

The Android SDK provides three different adapter implementations such as ArrayAdapter, CursorAdapter, and SimpleAdapter. An ArrayAdapter expects an array or a list as input, while CursorAdapter accepts the instance of the Cursor, and SimpleAdapter maps the static data defined in the resources. The type of adapter that suits your app need is purely based on the input data type.

The BaseAdapter is the generic implementation for all of the three adapter types, and it implements the IListAdapter, ISpinnerAdapter, and IDisposable interfaces. This means that the BaseAdapter can be used for ListView, GridView, “or Spinners.

For POIApp, we will create a subtype of BaseAdapter<T> as it meets our specific needs, works well in many scenarios, and allows the use of our custom layout.

Creating POIListViewAdapter

In order to create “POIListViewAdapter, we will start by creating a custom adapter “as follows:

  1. Create a new class named POIListViewAdapter.
  2. Open the POIListViewAdapter class file, make the class a public class, “and specify that it inherits from BaseAdapter<PointOfInterest>.

Now that the adapter class has been created, we need to provide a constructor “and implement four abstract methods.

Implementing a constructor

Let’s implement a “constructor that accepts all the information we will need to work with to populate the list.

Typically, you need to pass at least two parameters: an instance of an activity because we need the activity context while accessing the standard common “resources and an input data list that can be enumerated to populate the ListView. The following code shows the constructor from the code bundle:

private readonly Activity context;
private List<PointOfInterest> poiListData;
public POIListViewAdapter (Activity _context, List<PointOfInterest> _poiListData)
     :base()
{
   this.context = _context;
   this.poiListData = _poiListData;
}

Implementing Count { get }

The BaseAdapter<T> class “provides an abstract definition for a read-only Count property. In our case, we simply need to provide the count of POIs as provided in poiListData. The following code example demonstrates the implementation from the code bundle:

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

Implementing GetItemId()

The BaseAdapter<T> class “provides an abstract definition for a method that returns a long ID for a row in the data source. We can use the position parameter to access a POI object in the list and return the corresponding ID. The following code example demonstrates the implementation from the code bundle:

public override long GetItemId (int position)
{
     return position;
}

Implementing the index getter method

The BaseAdapter<T> class “provides an abstract definition for an index getter method that returns a typed object based on a position parameter passed in as an index. We can use the position parameter to access the POI object from poiListData and return an instance. The following code example demonstrates the implementation from the code bundle:

public override PointOfInterest this[int index] {
get{
     return poiListData [index];
     }
}

Implementing GetView()

The BaseAdapter<T> class “provides an abstract definition for GetView(), which returns a view instance that represents a single row in the ListView item. As in other scenarios, you can choose to construct the view entirely in code or to inflate it from a layout file. We will use the layout file we previously created. The following code example demonstrates inflating a view from a layout file:

view = context.LayoutInflater.Inflate (Resource.Layout.POIListItem, null, false);

The first parameter of Inflate is a resource ID and the second is a root ViewGroup, which in this case can be left null since the view will be added to the ListView item when it is returned.

Reusing row Views

The GetView() method is called” for each row in the source dataset. For datasets with large numbers of rows, hundreds, or even thousands, it would require a great deal of resources to create a separate view for each row, and it would seem wasteful since only a few rows are visible at any given time. The AdapterView architecture addresses this need by placing row Views into a queue that can be reused as they” scroll out of view of the user. The GetView() method accepts a parameter named convertView, which is of type view. When a view is available for reuse, convertView will contain a reference to the view; otherwise, it will be null and a new view should be created. The following code example depicts the use of convertView to facilitate the reuse of row Views:

var view = convertView;
if (view == null){
       view = context.LayoutInflater.Inflate (Resource.Layout.POIListItem, null);
}

Populating row Views

Now that we have an instance of the “view, we need to populate the fields. The View class defines a named FindViewById<T> method, which returns a typed instance of a widget contained in the view. You pass in the resource ID defined in the layout file to specify the control you wish to access.

The following code returns access to nameTextView and sets the Text property:

PointOfInterest poi = this [position];
view.FindViewById<TextView>(Resource.Id.nameTextView).Text = poi.Name;

Populating addrTextView is slightly more complicated because we only want to use the portions of the address we have, and we want to hide the TextView if none of the address components are present.

The View.Visibility property allows you to control the visibility property “of a view. In our case, we want to use the ViewState.Gone value if none of “the components of the address are present. The following code shows the “logic in GetView:

if (String.IsNullOrEmpty (poi.Address)) {
     view.FindViewById<TextView> (Resource.Id.addrTextView).Visibility = ViewStates.Gone;
} else{
   view.FindViewById<TextView>(Resource.Id.addrTextView).Text = poi.Address;
}

Populating the value for the distance text view requires an understanding of the location services. We need to do some calculation, by considering the user’s current location with the POI latitude and longitude.

Populating the list thumbnail image

Image downloading and” processing is a complex task. You need to consider the various aspects, such as network logic, to download images from the server, caching downloaded images for performance, and image resizing for avoiding the memory out conditions. Instead of writing our own logic for doing all the earlier mentioned tasks, we can use UrlImageViewHelper, which is a free component available in the Xamarin Component Store.

The Xamarin Component Store provides a set of reusable components, “including both free and premium components, that can be easily plugged into “any Xamarin-based application.

Using UrlImageViewHelper

The following steps will walk you “through the process of adding a component from the Xamarin Component Store:

  1. To include the UrlImageViewHelper component in POIApp, you can either double-click on the Components folder in the Solution pad, or right-click and select Edit Components.
  2. Notice that the component manager will be loaded with the already downloaded components and a Get More Components button that allows you to open the Components store from the window. Note that to access the component manager, you need to log in to your Xamarin account:
  3. Search for UrlImageViewHelper in the components search box available in the left-hand side pane. Now click on the download button to add your Xamarin Studio solution.
  4. Now that we have added the UrlImageViewHelper component, let’s go back to the GetView() method in the POIListViewAdapter class. Let’s take a look at the following section of the code:
    var imageView = view.FindViewById<ImageView> (Resource.Id.poiImageView);
    if (!String.IsNullOrEmpty (poi.Address)) {
    Koush.UrlImageViewHelper.SetUrlDrawable (imageView, poi.Image, Resource.Drawable.ic_placeholder);
    }

Let us examine how the preceding code snippet works:

  1. The SetUrlDrawable() method defined in the UrlImageViewHelper “component provides a logic to download an image using a single line of code. It accepts three parameters: an instance of imageView, where the image is to be displayed after the download, the image source URL, and the placeholder image.
  2. Add a new image ic_placeholder.png to the drawable Resources directory. While the image is being downloaded, the placeholder image will be displayed on imageView.
  3. Downloading the image over the network requires Internet permissions. The following section will walk you through the steps involved in defining permissions in your AndroidManifest.xml file.

Adding Internet permissions

Android apps must be “granted permissions while accessing certain features, such as downloading data from the Internet, saving an image in storage, and so on. You must specify the permissions that an app requires in the AndroidManifest.xml file. This allows the installer to show potential users the set of permissions an app requires at the time of installation.

To set the appropriate permissions, perform the following steps:

  1. Double-click on AndroidManifest.xml in the Properties directory in the Solution pad. The file will open in the manifest editor. There are two tabs: Application and Source, at the bottom of the screen, that can be used to toggle between viewing a form for editing the file and the raw XML, as shown in the following screenshot:
  2. In the” Required permissions list, check Internet and navigate to File | Save.
  3. Switch to the Source view to view the XML as follows:

Summary

In this article, we covered a lot about how to create user interface elements using different layout managers and widgets such as TextView, ImageView, ProgressBar, and ListView.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here