Search

Xamarin Android Listviews - Custom Activity Layout

Monday 20 October 2014

This post demonstrates how to use a custom activity layout with an Android ListView. The source code for the example is available here.
The previous examples have used the default list activity layout, which is just a full screen list view. Now we’ll use a custom layout to show the list view and a few other controls. The is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="All Players By Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSort" />
<Button
android:text="Just Notts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnJustNotts" />
<Button
android:text="Empty List"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnEmpty" />
<TextView
android:text="Nothing to show!"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/empty"
android:layout_margin="4dp" />
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@android:id/list" />
</LinearLayout>
This is a simple vertical linear layout. There are some buttons at the top which control what is displayed, a text view which is displayed if the list is empty, and the list itself. The list has the id “android:id/list” - this id tells the activity to use the list. The activity will display the element with the id “@android:id/empty” if there are no items in the list. It doesn’t have to be present and it can be used with any layout element.
In the code for the activity we need to use the custom layout in the OnCreate method…
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    this.SetContentView(Resource.Layout.CustomLayout);

    this.FindViewById<Button>(Resource.Id.btnSort).Click += this.btnSort_Click;
    this.FindViewById<Button>(Resource.Id.btnJustNotts).Click += this.btnJustNotts_Click;
    this.FindViewById<Button>(Resource.Id.btnEmpty).Click += this.btnEmpty_Click;

    data = Player.GetPlayers();
    this.ListAdapter = new PlayerAdapter(this, data);
}

No comments:

Post a Comment