Xamarin Android : GridView – Images,Text and OnClick

Xamarin Android : GridView – Images,Text and OnClick



Rating : 5/5 (2)




Introduction

GridView is an alternative to ListView that displays data in grids. You can set the number oc columns in your xml layout.GridView is just as powerful and customizable as ListView and they are used in the same way. Both use adapter to bind data to them. You can use an arrayadapter or baseadapter, in this case we use baseadapter as the base class for our custom adapter class. We inflate our custom xml layout into a viewitem here. We instantiate our adapter class passing in a list of data. We then set the adapter to our gridview.
The aim of this tutorial is to show how to render both images and text in a gridview. We also handle the itemclicks of our gridview.
You can find more details about GridView here.

Screenshot

  • Here's the screenshot of the project.

Xamarin Android Custom GridView Images and Text Example

Xamarin Android GridView Images Text

Common Questions this example explores

  • xamarin Android BaseAdapter tutorial.
  • Xamarin android custom gridview with images and text.
  • Custom GridView baseadapter android tutorial in C#.
  • Custom ListView with Images and Text C# Xamarin.
  • Handle ItemClicks in C# Xamarin GridView android.
  • Xamarin Android GridView onClick.

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 : GridView , 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;
namespace GridView_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 LsitAdapter class.
  • Extends BaseAdapter.
  • Supplies views to GridView on demand as the user scrolls up or down the grid.
  • Binds the data to views in each row.
using System;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Object = Java.Lang.Object;
namespace GridView_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 GridView.
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Runtime;
namespace GridView_Img_Txt
{
    [Activity(Label = "GridView_Img_Txt", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {//DECLARATIONS
        private GridView gv;
        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);
            gv = FindViewById<GridView>(Resource.Id.lv);
            //BIND ADAPTER
            adapter = new CustomAdapter(this, GetSpacecrafts());
            gv.Adapter = adapter;
            gv.ItemClick += gv_ItemClick;
        }
        /*
         * GRIDVIEW ITEM CLICK
         */
        void gv_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);
            s = new Spacecraft("Casini", Resource.Drawable.pioneer);
            spacecrafts.Add(s);
            return spacecrafts;
        }
    }
}

 

  • Content Layout.
  • Defines the views and widgets to be displayed inside the MainActivity.
  • Hosts our GridView 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">
    <GridView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2"
        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. Coming soon...
  • 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.

This is a xamarin android custom gridview with images and text example. Download the source code above.

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 *

    seventeen − fifteen =

    COMMENTS