C# Xamarin - Simple ListView and OnClick.

June 1, 2017 Oclemy Xamarin ListView 1 minute, 24 seconds

Hello guys.Welcome.Today we explore C# Xamarin - Simple ListView and OnClick.How to start off with ListView in Android Xamarin using ArrayAdapter and handle ItemClick events.

If you prefer a video version of this with more explanations,then check our video tutorial here: [embedyt] http://www.youtube.com/watch?v=s2J8b98nkxk[/embedyt]

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

namespace ListActivity_ArrayAdapter
{
    [Activity(Label = "ListView ArrayAdapter", MainLauncher = true, Icon = "@drawable/simplesmile")]
    public class MainActivity : Activity
    {

        ListView lv;
        ArrayAdapter adapter;
        ArrayList players;

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

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            //REFERENCE
            lv = FindViewById<ListView>(Resource.Id.lv);

            //FILL DATA
            getData();

            //ADAPTER

            adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, players);
            lv.Adapter = adapter;

            lv.ItemClick += lv_ItemClick;

        }

        void lv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Toast.MakeText(this, players[e.Position].ToString(), ToastLength.Short).Show();
        }

        private void getData()
        {
            players = new ArrayList();

            //ADD SOME DATA
            players.Add("Juan Mata");
            players.Add("Jesus Navas");
            players.Add("John Barnes");
            players.Add("John Doe");
            players.Add("Joel CampBell");
            players.Add("John Moh");
            players.Add("Jose Mou");
            players.Add("Joe Aurorah");

        }

    }
}

PART B : XML 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"
    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/lv" />
</LinearLayout>

Best Regards.

Comments