Xamarin Android ListViews Part 1 of 2




- January 31, 2016

Rest of the Story:

Continuing from my drawer example code…I have a fragment (About) where I want to show a number of rows.  There are a few ways of doing this but in my case I am going to use a ListView.
A ListView is an important UI component of Android applications, used everywhere from short lists of menu options to long lists of contacts or internet favorites.
In our example we have the following components that make up our Activity.

  • Activity the entire view
  • Red (our fragment)
  • Green (our listview)
  • Light Blue (our textview)
image

Because we are working with Fragments we build our code within the OnCreateView method. 

I have been able to do this within OnActivityCreated as well.

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    string[] recs = new string[2];
    recs[0] = "my first row";
    recs[1] = "my second row";  
    View view = inflater.Inflate(Resource.Layout.About, container, false);
    //_context = container.Context;             
    var listView = view.FindViewById<ListView>(Resource.Id.aboutListView);
    var adapter = new ArrayAdapter<string>(this.Activity, Resource.Layout.TextViewItem, recs);  //you can get context also by container.Context
    listView.Adapter = adapter;
    return view;
}  

In this example Resource.Layout.About is the name of my Fragment (public class AboutFragment : Fragment), Resource.Id.aboutListView is referencing the ListView that was placed in the About.axml (see below), and the Resource.Layout.TextViewItem (blue) represents each row.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android&quot;">http://schemas.android.com/apk/res/android"</a>
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/aboutListView" />
</LinearLayout>

This is another way of approaching inside the OnActivityCreated method

public override void OnActivityCreated(Bundle savedInstanceState)
{
    base.OnActivityCreated(savedInstanceState);    
    string[] recs = new string[2];
    recs[0] = "my first row";
    recs[1] = "my second row";
    var listView = this.Activity.FindViewById<ListView>(Resource.Id.aboutListView);            
    var adapter = new ArrayAdapter<string>(_context, Resource.Layout.TextViewItem, recs);
    listView.Adapter = adapter;
}  

TextViewItem.axml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/textItem"     android:textSize="44sp"     android:layout_width="fill_parent"     android:layout_height="wrap_content" />