Creating ListView In Xamarin Android

Introduction

In this article, we are going to learn how to create a simple ListView with item click in the Xamarin Android app.

Solution

Here are the steps required to create ListView in Xamarin Android app.

Step 1

Create/open your Android solution in Visual Studio or Xamarin Studio.

Step 2

Update your main.axml file inside your Resoursce/Layout folder, as shown below.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <ListView android:id="@+id/mainlistview" android:layout_height="match_parent" android:layout_width="match_parent"> </ListView>  
  4. </LinearLayout>  

Step 3

Initialize ListView in MainActivity, as shown below.

  1. public class MainActivity: Activity {  
  2.     string[] items;  
  3.     ListView mainList;  
  4.     protected override void OnCreate(Bundle bundle) {  
  5.         base.OnCreate(bundle);  
  6.         items = new string[] {  
  7.             "Xamarin",  
  8.             "Android",  
  9.             "IOS",  
  10.             "Windows",  
  11.             "Xamarin-Native",  
  12.             "Xamarin-Forms"  
  13.         };  
  14.         // Set our view from the "main" layout resource  
  15.         SetContentView(Resource.Layout.Main);  
  16.         mainList = (ListView) FindViewById < ListView > (Resource.Id.mainlistview);  
  17.         mainList.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, items);  
  18.     }  
  19. }  

Step 4

Initialize a ListView ItemClick event for handling the item click of ListView.

  1. mainList.ItemClick += (s, e) => {  
  2.     var t = items[e.Position];  
  3.     Android.Widget.Toast.MakeText(this, t, Android.Widget.ToastLength.Long).Show();  
  4. };  
Step 5

Now, run the application and you will see the output as given below.

Step 6

After clicking on ListView, the item toast message will display with title details.