Android – GridView example

By -
Problem: Simple GridView example
Description:

What do you say, is this simple GridView example?, I think it is not :) :). The main purpose of this post is to give demo for creating nicely laid GridView and also to make GridView more fancy.

Same as previous Android – ListView articles, we are going to create custom adapter for the GridView. I assume you are already aware of this or you have learnt it from my previous articles, If you aren’t aware about this then you should go through the previous article of Android – ListView.

And for understanding GridView XML layout attributes, just go through this article: Android – GridView – 1001 attributes to keep in mind

FYI, I have also attached example file for the easier download and implementation, example zip file is with full code (total 4 main files including 2 class files and 2 xml layout files).

Output ScreenShots:

Android GridView example

Android - GridView example

Solution:
GridViewExampleActivity.java
package com.technotalkative.gridviewexample;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewExampleActivity extends Activity {
    /** Called when the activity is first created. */

	private GridviewAdapter mAdapter;
	private ArrayList<String> listCountry;
	private ArrayList<Integer> listFlag;

	private GridView gridView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        prepareList();

        // prepared arraylist and passed it to the Adapter class
        mAdapter = new GridviewAdapter(this,listCountry, listFlag);

        // Set custom adapter to gridview
        gridView = (GridView) findViewById(R.id.gridView1);
        gridView.setAdapter(mAdapter);

        // Implement On Item click listener
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				Toast.makeText(GridViewExampleActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
			}
		});

    }

    public void prepareList()
    {
    	  listCountry = new ArrayList<String>();

    	  listCountry.add("india");
    	  listCountry.add("Brazil");
          listCountry.add("Canada");
          listCountry.add("China");
          listCountry.add("France");
          listCountry.add("Germany");
          listCountry.add("Iran");
          listCountry.add("Italy");
          listCountry.add("Japan");
          listCountry.add("Korea");
          listCountry.add("Mexico");
          listCountry.add("Netherlands");
          listCountry.add("Portugal");
          listCountry.add("Russia");
          listCountry.add("Saudi Arabia");
          listCountry.add("Spain");
          listCountry.add("Turkey");
          listCountry.add("United Kingdom");
          listCountry.add("United States");

          listFlag = new ArrayList<Integer>();
          listFlag.add(R.drawable.india);
          listFlag.add(R.drawable.brazil);
          listFlag.add(R.drawable.canada);
          listFlag.add(R.drawable.china);
          listFlag.add(R.drawable.france);
          listFlag.add(R.drawable.germany);
          listFlag.add(R.drawable.iran);
          listFlag.add(R.drawable.italy);
          listFlag.add(R.drawable.japan);
          listFlag.add(R.drawable.korea);
          listFlag.add(R.drawable.mexico);
          listFlag.add(R.drawable.netherlands);
          listFlag.add(R.drawable.portugal);
          listFlag.add(R.drawable.russia);
          listFlag.add(R.drawable.saudi_arabia);
          listFlag.add(R.drawable.spain);
          listFlag.add(R.drawable.turkey);
          listFlag.add(R.drawable.united_kingdom);
          listFlag.add(R.drawable.united_states);
    }
}
GridviewAdapter.java
package com.technotalkative.gridviewexample;

import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridviewAdapter extends BaseAdapter
{
	private ArrayList<String> listCountry;
	private ArrayList<Integer> listFlag;
	private Activity activity;

	public GridviewAdapter(Activity activity,ArrayList<String> listCountry, ArrayList<Integer> listFlag) {
		super();
		this.listCountry = listCountry;
		this.listFlag = listFlag;
		this.activity = activity;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listCountry.size();
	}

	@Override
	public String getItem(int position) {
		// TODO Auto-generated method stub
		return listCountry.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	public static class ViewHolder
	{
		public ImageView imgViewFlag;
		public TextView txtViewTitle;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder view;
		LayoutInflater inflator = activity.getLayoutInflater();

		if(convertView==null)
		{
			view = new ViewHolder();
			convertView = inflator.inflate(R.layout.gridview_row, null);

			view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
			view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);

			convertView.setTag(view);
		}
		else
		{
			view = (ViewHolder) convertView.getTag();
		}

		view.txtViewTitle.setText(listCountry.get(position));
		view.imgViewFlag.setImageResource(listFlag.get(position));

		return convertView;
	}
}
main.xml
<?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">
    
    <GridView 
    	android:layout_height="wrap_content" 
    	android:id="@+id/gridView1" 
    	android:layout_width="match_parent" 
    	android:numColumns="auto_fit"
    	android:horizontalSpacing="10dp"
    	android:verticalSpacing="10dp">
    </GridView>
</LinearLayout>
gridview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 	
	android:id="@+id/relativeLayout1"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:background="@drawable/border"
	android:padding="5dp">
    
    <ImageView 
    	android:layout_height="64dp" 
    	android:id="@+id/imageView1" 
    	android:layout_width="64dp" 
    	android:src="@drawable/icon" 
    	android:layout_alignParentTop="true" 
    	android:layout_centerHorizontal="true">
    </ImageView>
    
	<TextView 
		android:text="TextView" 
		android:layout_height="wrap_content"
		android:id="@+id/textView1" 
		android:layout_width="wrap_content"
		android:layout_below="@+id/imageView1" 
		android:layout_marginTop="2dp"
		android:layout_centerHorizontal="true"
		android:textSize="18sp"
		android:ellipsize="marquee"></TextView>
	
	
</RelativeLayout>

Download this example: https://github.com/PareshMayani/Android-GridView-Example

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • cheana

    quite interesting sir

  • Behzad Ahmady

    Thank you very much.
    Its a useful code.

  • ThemeBowl

    Nice Tutorial.How to load images from server?

    • http://www.technotalkative.com/ Paresh Mayani

      For loading images from web, you can use Asynchronous Image loading logic/class from this example: Asynchronous Image loading from web

  • http://www.facebook.com/profile.php?id=1166521072 Markus Bodmann

    Very Nice Tutorial

    • http://www.technotalkative.com/ Paresh Mayani

      Enjoy !!

  • roundcrisis

    Would be great if you had your code up on github/bitbuclket or similar and got the code from there. Easier to read and no need to use dodgy download sites

    • http://www.technotalkative.com/ Paresh Mayani

      Hey dear, you are right. But new articles are having download link pointing to/from this website only, earlier i was doing with WordPress.com blog so they linked to those dodgy sites, sorry for that. But soon i will upload on Github too. Thanks for the feedback.

    • http://www.technotalkative.com/ Paresh Mayani

      Hey dear, here you go for github :) https://github.com/PareshMayani?tab=repositories.

      • roundcrisis

        Thanks, BTW the “dear” sounds kind of weird.

  • Zajo

    very nice tutorial thank you
    but you should always use if(convertView==null || convertView.getTag() == null) in getView method because sometimes getTag() can return a null and that wouldn’t be good

  • Oleg

    Hello Paresh! Thank you for your job and example.

    One question. I have TabHost with 2 tabs and each tab has its gridView with images and text (2 differents activities). Each activity needs to call gridviewAdapter. Can I use the same one or i need to make differente gridviewAdapter for each activity? In case to use the same one, how changes the getView function? Thanks.

    • http://www.technotalkative.com/ Paresh Mayani

      Yes you can use the same GridViewAdapter if your requirement is to display same GridView with same look, you just need to pass your data to your GridViewAdapter.

      • Oleg

        And what about getView()? It has the resources of first layout and its elements.

        • http://www.technotalkative.com/ Paresh Mayani

          I would suggest you to understand the getView() given above, where we are inflating gridview_row.xml which is row/item layout file which you want for every item.

  • Ajinkya

    I have URL’s of images and want to show those images as well as text in Grid View….

  • Mohan Mugi

    lovely

  • luffy

    Thanks! Nice tutorial. But i have a question. When I try to set the android:ellipsize=”none” on the gridview_row.xml and then make the 1st or 2nd list a longer text E.g listCountry.add(“india testing a longer text on a gridview”); notice that when you scroll the gridview down and scroll upward the image with long text doesn’t display correctly(image crop). Do you have any workaround about it? Thanks in advance.

  • Nikita Sukhadiya

    Thank u so so so much sir..
    it really helpful for me…..
    Thank You….