Xamarin Android : ListView – Images,Text and ItemClick

Xamarin Android : ListView – Images,Text and ItemClick



Rating : 5/5 (2)




Introduction

My guess is that everybody knows or has used a ListView. Not only is it easy to use but it's also extremely powerful. ListView doesn't know or care about the details of the views it hosts. It requests views on demand from the ListAdapter when just about to display them.
This makes ListViews quite powerful and customizable and they can be used to display various types of data. We make use of this by making a custom listview with images and text. The images get displayed just next to the next in our Listview. If the user clicks a single ListView, item, we handle the itemclick event and show a toast message.
You can find more details about ListView here.

Screenshot

  • Here's the screenshot of the project.

Xamarin Android Custom ListView Images and Text Example

Xamarin Android ListView Images Text

Common Questions this example explores

  • Android Custom ListView in xamarin.
  • Custom ListView with Images and Text C# Xamarin.
  • Handle ItemClicks in C# Xamarin ListView android.
  • Render image and text in ListView.
  • Xamarin Android BaseAdapter Example with ListView.

Tools Used

This example was written with the following tools:

  • Windows 8
  • Visual Studio IDE
  • Genymotion Emulator
  • Language : C#
  • Platform : Xamarin Android
  • Topic : Xamarin Android ListView with Images and Text.
  • Sub-Topics : ListView, BaseAdapter, ItemClicks

Source Code

Lets jump directly to the source code.

Spacecraft.csCustomAdapter.csMainActivity.csMain.axmlModel.axmlVideo/PreviewDownload
  • Our Data Object POCO class.
  • Represents a single Spacecraft with its properties like name and image.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace ListView_Img_Txt
{
    class Spacecraft
    {
        private String name;
        private int image;
        public Spacecraft(string name, int image)
        {
            this.name = name;
            this.image = image;
        }
        public string Name
        {
            get { return name; }
        }
        public int Image
        {
            get { return image; }
        }
    }
    
}

 

  • Our ListAdapter class.
  • Extends BaseAdapter.
  • Supplies views to ListView on demand as the user scrolls up or down the list.
  • Binds the data to views in each row.
  • We also include ViewHolder class.
  • ViewHolder is going to hold our views for recycling.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Object = Java.Lang.Object;
namespace ListView_Img_Txt
{
    class CustomAdapter : BaseAdapter
    {
        private readonly Context c;
        private readonly JavaList<Spacecraft> spacecrafts;
        private LayoutInflater inflater;
        /*
         * CONSTRUCTOR
         */
        public CustomAdapter(Context c, JavaList<Spacecraft> spacecrafts)
        {
            this.c = c;
            this.spacecrafts = spacecrafts;
        }
        /*
         * RETURN SPACECRAFT
         */
        public override Object GetItem(int position)
        {
            return spacecrafts.Get(position);
        }
        /*
         * SPACECRAFT ID
         */
        public override long GetItemId(int position)
        {
            return position;
        }
        /*
         * RETURN INFLATED VIEW
         */
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            //INITIALIZE INFLATER
            if (inflater == null)
            {
                inflater = (LayoutInflater)c.GetSystemService(Context.LayoutInflaterService);
            }
            //INFLATE OUR MODEL LAYOUT
            if (convertView == null)
            {
                convertView = inflater.Inflate(Resource.Layout.Model, parent, false);
            }
            //BIND DATA
            CustomAdapterViewHolder holder = new CustomAdapterViewHolder(convertView)
            {
                NameTxt = {Text = spacecrafts[position].Name}
            };
            holder.Img.SetImageResource(spacecrafts[position].Image);
            //convertView.SetBackgroundColor(Color.LightBlue);
            return convertView;
        }
        /*
         * TOTAL NUM OF SPACECRAFTS
         */
        public override int Count
        {
            get { return spacecrafts.Size(); }
        }
    }
    class CustomAdapterViewHolder : Java.Lang.Object
    {
        //adapter views to re-use
         public TextView NameTxt;
        public ImageView Img;
        public CustomAdapterViewHolder(View itemView)
        {
            NameTxt = itemView.FindViewById<TextView>(Resource.Id.nameTxt);
            Img = itemView.FindViewById<ImageView>(Resource.Id.spacecraftImg);
        }
    }
}

 

  • Launcher activity.
  • Extends Activity.
  • Main.axml inflated as the contentview for this activity.
  • We initialize views and widgets inside this activity.
  • We also associate the ListView with its adapter here.
  • We handle itemclicks here for our custom ListView.
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Runtime;
namespace ListView_Img_Txt
{
    [Activity(Label = "ListView_Img_Txt", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        //DECLARATIONS
        private ListView lv;
        private CustomAdapter adapter;
        private JavaList<Spacecraft> spacecrafts;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            lv = FindViewById<ListView>(Resource.Id.lv);
            //BIND ADAPTER
            adapter = new CustomAdapter(this, GetSpacecrafts());
            lv.Adapter = adapter;
            lv.ItemClick += lv_ItemClick;
        }
        /*
         * LISTVIEW ITEM CLICK
         */
        void lv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Toast.MakeText(this, spacecrafts[e.Position].Name, ToastLength.Short).Show();
        }
        /*
         * DATA SOURCE 
         */
        private JavaList<Spacecraft> GetSpacecrafts()
        {
            spacecrafts = new JavaList<Spacecraft>();
            Spacecraft s;
            s = new Spacecraft("Enterprise", Resource.Drawable.enterprise);
            spacecrafts.Add(s);
            s = new Spacecraft("Hubble", Resource.Drawable.hubble);
            spacecrafts.Add(s);
            s = new Spacecraft("Kepler", Resource.Drawable.kepler);
            spacecrafts.Add(s);
            s = new Spacecraft("Spitzer", Resource.Drawable.spitzer);
            spacecrafts.Add(s);
            s = new Spacecraft("Rosetter", Resource.Drawable.rosetta);
            spacecrafts.Add(s);
            s = new Spacecraft("Voyager", Resource.Drawable.voyager);
            spacecrafts.Add(s);
            s = new Spacecraft("Opportunity", Resource.Drawable.opportunity);
            spacecrafts.Add(s);
            s = new Spacecraft("Pioneer", Resource.Drawable.pioneer);
            spacecrafts.Add(s);
            s = new Spacecraft("Challenger", Resource.Drawable.challenger);
            spacecrafts.Add(s);
            s = new Spacecraft("WMAP", Resource.Drawable.wmap);
            spacecrafts.Add(s);
            s = new Spacecraft("Columbia", Resource.Drawable.columbia);
            spacecrafts.Add(s);
            return spacecrafts;
        }
    }
}

 

  • Content Layout.
  • Defines the views and widgets to be displayed inside the MainActivity.
  • Hosts our ListView widget.
<?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:background="#009688"
    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>

 

  • Row Item Layout.
  • Inflated as the viewitem of our ListView.
  • Defines the views and widgets to be displayed inside each row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#ffffff"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/spacecraftImg"
            android:src="@drawable/enterprise"
            android:layout_width="150dp"
            android:layout_height="wrap_content" />
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="10dp"
                android:textColor="#f38630"
                android:textStyle="bold"
                android:layout_alignParentLeft="true" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

 

  • Video version of this tutorial.

Xamarin Examples S1E4 : ListView - Images, Text, ItemClick

  • Download the Project below:

How To Run

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Open the Visual Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >Open> Project/Solution.
  6. That's it.

Conclusion.

We saw a Xamarin Android Custom ListView with Images and Text example.

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.



Rating :

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    5 + 9 =

    COMMENTS