Home > Tutorials > Custom grid view of applications

Custom grid view of applications


Today, I’ll guide you how to create a simple grid view that displays the list of applications, look at screenshot below:

Application Grid Screenshot

Application Grid Screenshot

Similar to ListView, the GridView is the view control that displays its items like a grid, so you just need to work around similar to the PhoneBook ListView in my previous post.

A – Create the Project

Project Name: Application Grid

Application Name: Application Grid

Build Target: Android 2.3.3

Package Name: pete.android.study

Create Activity: MainActivity

Min SDK: 10

B – Sketch the Layout

Like the list view, we all need to construct 2 layout:

+ one layout for each item inside the grid

+ one layout for the main grid view display

1. Grid Item Layout

Very simple, we create one image view to display application icon and one text view to display application name.

Put this file: layout_appinfo.xml into /res/layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:gravity="center_horizontal"
  >

  <ImageView
      android:id="@+id/ivIcon"
      android:layout_width="48dip"
      android:layout_height="48dip"
      android:scaleType="centerCrop"
  />
  <TextView
  	  android:id="@+id/tvName"
  	  android:layout_width="72dip"
  	  android:layout_height="wrap_content"
  	  android:gravity="center"
  	  android:textStyle="bold"
  />

</LinearLayout>

Remember to set image view “android:scaleType=”centerCrop”” to make image bitmap fit into the box. Also, set text alignment to “center” to make it display nicely with top icon.

2. Main Layout

Just put a grid view inside. Put this file main.xml into /res/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"
    >

	<GridView
		android:id="@+id/gvMain"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:numColumns="4"
		android:columnWidth="72dip"
		android:gravity="center"
		android:stretchMode="columnWidth"
		android:padding="10dip"
		android:verticalSpacing="10dip"
		android:horizontalSpacing="10dip"
	/>

</LinearLayout>

C – Class Design: On the Idea

Application Grid: Class Diagram

Application Grid: Class Diagram

D – From Design to Coding

1. AppInfo: (AppInfo.java)  the entity class which holds information of application including: application icon and application name.

package pete.android.study;

import android.graphics.Bitmap;

public class AppInfo {
	private Bitmap mIcon;
	private String mName;

	public AppInfo(Bitmap icon, String name) {
		mIcon = icon;
		mName = name;
	}

	public void setIcon(Bitmap icon) {
		mIcon = icon;
	}
	public Bitmap getIcon() {
		return mIcon;
	}

	public void setName(String name) {
		mName = name;
	}
	public String getName() {
		return mName;
	}

}

2. AppInfoAdapter: (AppInfoAdapter.java) the adapter to handle the list of application info in the grid view.

package pete.android.study;

import java.util.List;

import android.content.Context;
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 AppInfoAdapter extends BaseAdapter {
	private Context mContext;
	private List<AppInfo> mListAppInfo;

	public AppInfoAdapter(Context context, List<AppInfo> list) {
		mContext = context;
		mListAppInfo = list;
	}

	@Override
	public int getCount() {
		return mListAppInfo.size();
	}

	@Override
	public Object getItem(int position) {
		return mListAppInfo.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AppInfo entry = mListAppInfo.get(position);

		if(convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(mContext);
			convertView = inflater.inflate(R.layout.layout_appinfo, null);
		}

		ImageView ivIcon = (ImageView)convertView.findViewById(R.id.ivIcon);
		ivIcon.setImageBitmap(entry.getIcon());

		TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
		tvName.setText(entry.getName());

		return convertView;
	}
}

3. MainActivity: (MainActivity.java) the entry point to the application

package pete.android.study;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends Activity {

	private GridView mGridMain;

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

        mGridMain = (GridView)findViewById(R.id.gvMain);
        Resources res = getResources();
        List<AppInfo> listAppInfo = new ArrayList<AppInfo>();
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_browser), "Internet"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_clock), "Clock"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_display), "Display"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_favorite), "Favorite"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_home), "Home"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_mail), "Mail"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_media), "Media"));
        mGridMain.setAdapter(new AppInfoAdapter(this, listAppInfo));

    }
}

E – Note

– For the layout of each item in the grid view, if the LinearLayout you don’t set “android:gravity=”center_horizontal”“, then it will display very ugly.

– Make sure you put your application bitmap into /drawble

– Try to practice with this kind of simple application to understand the idea of Adapter in GridView, and ListView in my previous post.

– Think about design when u’re good at coding.

F – Get the Sample Project by Pete

Pick your favorite server: Mediafire | Rapidshare | FreeFileHosting | Megaupload

G – Final Words

– Have you learned something?

– Hope you enjoy it!

– Feel free to ask, comment, and suggest below; you’re all welcomed!

H – Update on Request

1. Alfox on request to add extra click event for GridView

– Since this is a GridView so we need to implement AdapterView.OnItemClickListener, and it must be set to GridView object, and not in the Adapter. This is a common mistake when people try to implement ClickListener on the Adapter!

– Here I will add this listener to add functionality that a Toast is displayed with the item name when users click on an item of GridView. It requires some changes for above source code, like below:

(1) Update the AppInfoAdapter class (AppInfoAdapter.java) to have a ViewHolder pattern which will cache data.

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AppInfo entry = mListAppInfo.get(position);
		ViewHolder holder = null;

		if(convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(mContext);
			convertView = inflater.inflate(R.layout.layout_appinfo, null);
			holder = new ViewHolder();
			holder.ivIcon = (ImageView)convertView.findViewById(R.id.ivIcon);
			holder.tvName = (TextView)convertView.findViewById(R.id.tvName);
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder)convertView.getTag();
		}

		holder.ivIcon.setImageBitmap(entry.getIcon());
		holder.tvName.setText(entry.getName());

		return convertView;
	}

	static class ViewHolder {
		ImageView ivIcon;
		TextView tvName;
	}

(2) Add listener to the GridView and implement the listener to display information to Toast view.

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

        mGridMain = (GridView)findViewById(R.id.gvMain);
        Resources res = getResources();
        List<AppInfo> listAppInfo = new ArrayList<AppInfo>();
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_browser), "Internet"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_clock), "Clock"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_display), "Display"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_favorite), "Favorite"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_home), "Home"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_mail), "Mail"));
        listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_media), "Media"));
        mGridMain.setAdapter(new AppInfoAdapter(this, listAppInfo));

        mGridMain.setOnItemClickListener(mItemClickListener); // add a ItemClickListener

    }
    // our handle for listener
    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
			ViewHolder holder = (ViewHolder)view.getTag();
			if(holder == null) {
				return;
			}
			Toast.makeText(MainActivity.this, "You have clicked on item '" + holder.tvName.getText() + "'", Toast.LENGTH_SHORT).show();
		}
	};

(3) Rebuild and run your application…free to click on GridView item to see how it works!!!

 

Hope you enjoy it!

Cheers,

Pete Houston

Advertisements
  1. February 10, 2014 at 5:00 pm

    This is a great tutorial Pete!

    However, I have inquiries. I am developing an app where I am going to put certain applications in a gridView (meaning it’s not all application to populate the GridView) and from there, when the user click the icon of an application, the application will start. How can I do that?

  2. April 20, 2012 at 6:27 pm

    Thank you somuch for this useful tutorial saved my time……

  3. supriya`
    April 12, 2012 at 6:55 pm

    hi,thnx for the great tut..
    i wanted to know can i use this base adapter for listview?as i want to do view switching thing.means right now i am displaying all list of files of phonw in listview now i want to show that list in grid manner,but i dont want to use gridview.as if i use gridview i have to write separate on clicklistner and all.so just want to know.or if nay other way is there please let me know ASAP..
    Thnx in advance, Any help will be appriciated.

  4. Harpreet.
    January 19, 2012 at 5:14 pm

    For Intents use in this code:: refer::

    http://stackoverflow.com/questions/6024374/android-gridview-need-to-open-different-intents

    Just go to last code, you’ll know what to do and where.

    Thanks a lot for this blog, it was really very helpful in my assignment.

  5. Harpreet.
    January 19, 2012 at 5:12 pm

    Thanks a lot, This blog was very helpful. The reat what i added in it is::

    private OnItemClickListener mItemClickListener = new OnItemClickListener()
    {
    public void onItemClick(AdapterView parent, View view, int pos, long id)
    {
    ViewHolder holder = (ViewHolder)view.getTag();
    if(holder == null)
    {
    return;
    }
    Toast.makeText(MainGridActivity.this, “You have clicked on item:: ” + holder.text.getText() , Toast.LENGTH_SHORT).show();

    Intent intent = null;

    if(pos == 0)
    {
    intent = new Intent(view.getContext(), ServiceAirTravel.class);
    }

    startActivity(intent);

    }
    };

    I used the link :: http://stackoverflow.com/questions/6024374/android-gridview-need-to-open-different-intents

    Thanks to all of you, for your suggestions.

  6. Anurag
    December 26, 2011 at 7:32 pm

    I have also tried the above way to create a gridview with dynamic listing of applications and was able to display the applications listing..But the click event on the grid items does not work. Nothing happens when i click any application icon. The OnItemClickListener does not capture any click event.

  7. seyyah
    December 25, 2011 at 6:37 am

    Hi thanx for example
    I have a queation
    how can I insert a hyperlink?
    // listAppInfo.add(new AppInfo(BitmapFactory.decodeResource(res, R.drawable.app_clock), “Clock”));

  8. December 6, 2011 at 10:58 pm

    What an all ’round great blog.

  9. November 9, 2011 at 8:37 pm

    This is awesome!!! very nice article, thanks for sharing with us. Its help me lot and this link
    http://mindstick.com/Articles/4ed9bee8-c214-471f-bcc5-3dd743dbb2ab/?Using%20GridView%20in%20Android%20Application

    also helped me to complete my task.

    Thanks !!

  10. Nanda
    November 9, 2011 at 5:48 am

    hola que pena, esta linea me sale mala
    convertView = inflater.inflate (R.layout.layout_appinfo, null );
    perola parte de R.layout.layout_appinfo quisiera saber esto donde lo declaro o en donde esta nombrado gracias 🙂

    • November 9, 2011 at 8:43 am

      Please read my article carefully, it’s all there.
      Anyway, I don’t know Spanish..

  11. September 15, 2011 at 9:08 am

    Dave Agaba :

    Yeah, that doesn’t to be the problem. I have checked twice. Could you please link your source code or any similar code that works with a base adapter with a grid view that is clickable. I can’t seem to get this done, even with a listview base adapter!

    Thanks :-)

    Well then I have no idea what you have done, my friends just do copy & paste exactly all my code above into a new project and build, it runs perfectly w/o any problems. Just try again with my settings and code above. The clickable thing doesn’t easy as you think if you don’t have the concept of Android View, of how it works, like buddy Alfox below.
    If still problem, upload your project to Mediafire, post link here, I’ll fix it for you.

  12. Dave Agaba
    September 14, 2011 at 3:55 am

    Hey thanks for the tutorial. It made sense all the way until I ran that code and it failed to work. On further debugging, i noted that this code below was responsible for the error:

    mGridMain.setAdapter(new AppInfoAdapter(this, listAppInfo));

    Looking through the debugger, I am informed that I have a null point exception and this is not explained further.

    As you may imagine, this is rather frustrating esp with this similar code, I could do so much including designing a list view.

    Any ideas as to what might have happened?

    • September 14, 2011 at 9:13 pm

      No, my code is fine, you might wanna check your mGridMain is NULL or not :). If it’s NULL, please verify whether mGridMain is found or not : mGridMain = (GridView)findViewById(R.id.gvMain);

      • Dave Agaba
        September 15, 2011 at 1:36 am

        Yeah, that doesn’t to be the problem. I have checked twice. Could you please link your source code or any similar code that works with a base adapter with a grid view that is clickable. I can’t seem to get this done, even with a listview base adapter!

        Thanks
        🙂

  13. Alfox
    July 14, 2011 at 2:38 pm

    Thank You! very very helpful, I have learn another think, just thanks to you

    • July 14, 2011 at 2:53 pm

      You’re welcome anytime 🙂 Feel free to introduce my site to others to help other learning too ^^!

  14. July 14, 2011 at 11:17 am

    I’ve updated your request. Enjoy learning Android from my blog 🙂

  15. Alfox
    July 13, 2011 at 1:35 pm

    if you can make an example, I will very greatful!
    sorry but I am not very expert 🙂

    • July 13, 2011 at 10:15 pm

      Ok! I will update it a sample for you asap 🙂 just wait for a while 🙂

      • Alfox
        July 14, 2011 at 1:51 am

        THANKS!!!!! really nice!

  16. Alfox
    July 12, 2011 at 10:13 pm

    Hello!
    helpful tutorial, but if I want add an onClick event on each image, how I can do?
    Thanks!

    • July 13, 2011 at 9:11 am

      There are many ways to do this, like:
      1. Add a OnClickListener for each AppInfo
      2. Implement OnClickListener right on AppInfoAdapter
      ..

  1. April 29, 2013 at 5:44 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: