GridView

Android GridView Example

One of the most usefull layouts in Android is the GridView. GridView organizes the items of your screen in a two-dimensional array (a grid…). In this tutorial you are going to see two examples of GridView. In the first part we see the normal use of GridView. In the second part we create our own customized GridView.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

 

Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project and click Next.

You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

Normal GridView Example

1.Create the main layout

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="50dp"
    android:gravity="center"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth" >

</GridView>

2. Code

Go to the java file that contains the code of the activity you’ve just created:

And paste the following code:

package com.javacodegeeks.android.androidgridviewexample;

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

public class MainActivity extends Activity {

	GridView grid;

	static final String[] letters = new String[] { 
			"A", "B", "C", "D", "E",
			"F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O",
			"P", "Q", "R", "S", "T",
			"U", "V", "W", "X", "Y", "Z"};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		grid = (GridView) findViewById(R.id.gridView);

		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, letters);

		grid.setAdapter(adapter);

		grid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v, int position, long id) {
			   Toast.makeText(getApplicationContext(),
				((TextView) v).getText(), Toast.LENGTH_SHORT).show();
			}
		});

	}

}

3. Run the application

Go ahead and run the application to see how the layout looks on your emulator. This is the main screen of our application:

And when you click on a letter:

Download Eclipse Project

This was the first part of the Android GridView Example. Download the Eclipse Project of the first part of this tutorial: AndroidGridViewExample_1.zip

Custom GridView Example

For this part you can create a new Android Project if you want, but I’m going to use the old one.

1. Create the custom Layout

The first thing you have to do for this part is to create a new xml Layout file that will describe the Layout of our custom GridView.

Go to the Package Explorer and right click on the res/layout folder. Select New -> Other -> Android -> Android XML Layout File. And click Next:

Then specify the name of the file and the Layout type and click Finish:

As you will see in the Package Explorer the new /res/layout/countries.xml file has been created:

Open that file and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/flag"
        android:layout_width="50sp"
        android:layout_height="50sp"
        android:layout_marginRight="10sp">
    </ImageView>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:layout_marginTop="15sp"
        android:textSize="15sp" >
    </TextView>

</LinearLayout>

Now, go back to the /res/layout/main.xml and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="160dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

</GridView>

2. Adding pictures in the appropriate project folder

As you would have noticed in the Package explorer, there are 4 folders that contain the image resources of the project :

  1. res/drawable-hdpi
  2. res/drawable-ldpi
  3. res/drawable-mdpi
  4. res/drawable-hdpi

You can copy the images you want to put in you’re application in any one of these folders.  Android SDK will automatically recognize any images you put on any one of these folders as drawable resources. So, copy the images in the folder you want. If the image does not appear in the Package Explorer under the folder you’ve copied it into, right click on the project name and select Refresh. Now the image should be under the correct folder. As you can see, I have four images in res/drawable-hdpi:

3. Create a Custom ArrayAdapter

To create a custom GridView you have to make your own BaseAdapter. To do that you have to to create a new class that will extend BaseAdapter.

Go to the Package Explorer and right click on the package (in our case com.javacodegeeks.android.androidgridvieexample):

Select New -> Class. Put the appropriate attributes as shown in the picture below:

As you will see a new java file has been created:

Open that file and paste the following code :

package com.javacodegeeks.android.androidgridviewexample;

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 MyAdapter extends BaseAdapter {
	private Context context;
	private final String[] countries;

	public MyAdapter(Context context, String[] countries) {
		this.context = context;
		this.countries = countries;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;

		if (convertView == null) {

			gridView = new View(context);

			gridView = inflater.inflate(R.layout.countries, null);

			TextView textView = (TextView) gridView.findViewById(R.id.label);

			textView.setText(countries[position]);

			ImageView flag = (ImageView) gridView .findViewById(R.id.flag);

			String mobile = countries[position];

			if (mobile.equals("Greece")) {
				flag.setImageResource(R.drawable.greekflag);
			} else if (mobile.equals("Germany")) {
				flag.setImageResource(R.drawable.germanflag);
			} else if (mobile.equals("Italy")) {
				flag.setImageResource(R.drawable.italianflag);
			} else {
				flag.setImageResource(R.drawable.britishflag);
			}

		} else {
			gridView = (View) convertView;
		}

		return gridView;
	}

	@Override
	public int getCount() {
		return countries.length;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

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

}

Now, go back to MainActivity.java and paste the following code :

package com.javacodegeeks.android.androidgridviewexample;

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

public class MainActivity extends Activity {

	GridView gridView;

	static final String[] MOBILE_OS = new String[] { "Greece", "Germany","Italy", "Britain" };

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		gridView = (GridView) findViewById(R.id.gridView);

		gridView.setAdapter(new MyAdapter(this, MOBILE_OS));

		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v,
					int position, long id) {
				Toast.makeText(
						getApplicationContext(),
						((TextView) v.findViewById(R.id.label)).getText(), Toast.LENGTH_SHORT).show();

			}
		});

	}

}

4. Run the application

This is the main screen of our Application:

Now, when you click on an item:

Download Eclipse Project

This was the second part of the Android GridView Example. Download the Eclipse Project of the second part of this tutorial: AndroidGridViewExample_2.zip

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button