Android Tutorial: GridView Layout

In this post a small android app is build which makes use of the gridview layout. The app consist of a gridview with images from the Android Play Market, when clicking on each of the items a dialog pop-up will appear with a small text with either a cancel of download button.The following screenshots show what we will build in this tutorial. We will use the GridView layout, ArrayAdapter and a Dialog window.

 

 

 

 

 

 

 

 

First we set our layout for the GridView, open your main XML and make sure your GridView Layout is similar to the one below. You can adjust the spacings and Number of Columns to your own preference.

<?xml version="1.0" encoding="utf-8"?>  

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gv_demo"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"   
    android:numColumns="2"
    android:columnWidth="90dp"
    android:paddingTop="15dp"
    android:horizontalSpacing="5dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:stretchMode="columnWidth"
     >
  </GridView>

After the user clicks on one of the items in the Grid a pop-up will appear with a small promotion text and a link to the play market. This content and links are set in a separate value folder: arrays.xml.  Arrays.xml is populated with two string arrays one for the content in the pop-up and one for the links to the play market.  Each are separated by and <Item> tag.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="appdescription">
        <item>Convert Office Documents to high-quality PDF Documents just like Adobe Acrobat
				Adobe CreatePDF brings the same high-quality PDF creation as Adobe Acrobat to your Android Tablet and Smartphone. Convert all your Office, Photoshop, Illustrator, InDesign, Image, Text, and RTF files to PDF, and share the converted PDF using Adobe CreatePDF application.</item>
        <item>Box for Android lets you view and share files from anywhere!
				With 5GB free, Box makes it easy to access and edit your files, share content and stay connected with your team from anywhere on any device.</item>
        <item>CamCard is a professional business card reader and business card scanner. Simply take a picture of a business card, CamCard recognizes the business card and saves contact information in Card Holder or your Address Book. Then feel at ease to manage cards with CamCard - business card reader and business card scanner.</item>
        <item>View Microsoft Word, Excel and PowerPoint Files  All in 1 App!FREE. View native Microsoft Word, Excel and PowerPoint files and attachments with Documents To Go Main App</item>
        <item>Compare flights, hotels and rental cars, track flights, get cheap travel deals.
				The #1 Mobile Travel app includes flight and car search, hotel search and booking, Flight tracker and My Trips, so you have your itinerary at your fingertips. And of course, KAYAK for Android is free.</item>
        <item>For Professionals Going Places. Get on-the-go access to your professional network with the LinkedIn app for Android.</item>
        <item>Get instant access to your Salesforce information on your Android device.Now with edit and create! Choose between:</item>
        <item>TripIt is the world’s easiest way to organize and share your travel plans.
				No more searching through your inbox to find your airline reservation. No more scrambling to get directions to your hotel. No more worrying about what time your business dinner starts. With TripIt, everything you need to get you where you’re going and back again is at your fingertips—on your smartphone, tablet or online at tripit.com.</item>
        <item>Evernote is an easy to use, free app that helps you remember everything across all of the devices you use. Stay organized, save your ideas and improve productivity. Evernote lets you take notes, capture photos, create to-do lists, record voice reminders and makes these notes completely searchable, whether you are at home, at work, or on the go.</item>
   	<item >Wunderlist for Android will boost your productivity. Organize your to-do lists on the go and synchronize them with your free Wunderlist account. View and modify your tasks on Windows, Mac, iPhone, iPad and the Web. Hundreds of thousands of people worldwide use Wunderlist everyday. Wunderlist - your tasks anywhere, anytime.</item>
   </string-array> 
   
   <string-array name="links">
       <item>market://details?id=com.adobe.createpdf</item>
        <item>market://details?id=com.box.android</item>
         <item>market://details?id=com.intsig.BCRLite</item>
        <item>market://details?id=comdataviz.docstogo</item>
         <item>market://details?id=com.kayak.android</item>
         <item>market://details?id=com.linkedin.android</item>
         <item>market://details?id=com.salesforce.crm</item>
         <item>market://details?id=com.tripit</item>
         <item>market://details?id=com.evernote</item>
         <item>market://details?id=com.wunderkinder.wunderlistandroid</item>
   </string-array> 
   
</resources>

Now we have set the layout and the content in arrays.xml we can start programming the java classes to make it all work :).

First make a new class in your project and name it GridViewContent and let it extend BaseAdapter. First build the Constructor and set a context variable.

public class GridViewContent extends BaseAdapter {

private Context context;

public GridViewContent(Context c){

context = c;

}

Eclipse will ask you to implement the unimplemented methods, implement them.

Make an Array list variable with all the images which you want to set in your GridView

public int [] gv_fill = {

R.drawable.banneradobe,
R.drawable.bannerbox,
R.drawable.bannercamcard,
R.drawable.bannerdocument2go,
R.drawable.bannerkayak,
R.drawable.bannerlinkedin,
R.drawable.bannersalesforce,
R.drawable.bannertripit,
R.drawable.bannervernote,
R.drawable.bannerwunderlist

};

Set in the getCount() method gv_fill.length so the ArrayAdapter know how many items are in your GridView.
Link in your Object getItem method the itemID to the position in your GridView. Note that we have 10 banners in total, but the Array counts from 0-9.
In the View GetView method your array list is set to the GridView. In this method a simple new ImageView is created and set to the GridView. In addition your can set some parameters like alignment and the size of the individual gridview item.

The complete code for the GridViewContent class is:

package com.example.gridlayout;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class GridViewContent extends BaseAdapter {

	private Context context;

	public int [] gv_fill = {
		R.drawable.banneradobe,
		R.drawable.bannerbox,
		R.drawable.bannercamcard,
		R.drawable.bannerdocument2go,
		R.drawable.bannerkayak,
		R.drawable.bannerlinkedin,
		R.drawable.bannersalesforce,
		R.drawable.bannertripit,
		R.drawable.bannervernote,
		R.drawable.bannerwunderlist

	};

		public GridViewContent(Context c){
	        context = c;
	    }

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

	@Override
	public Object getItem(int position) {
		return gv_fill[position];

	}

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

	@Override
	public View getView(int position, View arg1, ViewGroup arg2) {

		ImageView imageView = new ImageView(context);
        imageView.setImageResource(gv_fill[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setLayoutParams(new GridView.LayoutParams(350, 200));
        return imageView;
    }

}

Now open your MainActivity java.

First we create the reference to the GridView widget which we have set in our XML layout. Then we set the GridView to the adapter which we created in the GridView content class and implement an onItemClickListener.

Now the only thing which is left is that we need to program what needs to happen when we click on a single item in our GridView.

First we create the variables which set the values in the Arrays. Remember these are the values we have created in our Arrays.xml. We just simple retrieve these values via getStringArray and pass the position.

Secondly we create a new dialog via AlertDialog.builder. The dialog content we can set via setMessage and link it to our array variable appdescription. In addition we set the title of the dialog window to “More  about the app”.

A bit more complex is that we want in case the user selects download that the app routes the user to the android plat market to download the app. We do this by implementing an onclicklistener on the PossitveButton (in our case “download”).  We create a new Intent and because we are directing the user to an external destination we use Uri.parse(marketlinks). Note that the parameter marketlinks refer to the variable we have set based on our array.xml.

package com.example.gridlayout;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class MainActivity extends Activity {

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

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

        gridView.setAdapter(new GridViewContent(this));
        gridView.setOnItemClickListener(itemClickListener);
    }
        private OnItemClickListener itemClickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<!--?--> arg0, View view, int position,
					long id) {

				String[] appdescr = getResources().getStringArray(R.array.appdescription);
	            final String appdescription = appdescr[position];
	            String[] links = getResources().getStringArray(R.array.links);
	            final String marketlinks = links[position];
	            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);

	                        dlgAlert.setMessage(appdescription);
	                        dlgAlert.setTitle("More about the app:");
	                        dlgAlert.setPositiveButton("Download", new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int which) {
	                                Intent i = new Intent(Intent.ACTION_VIEW);
	                              i.setData(Uri.parse(marketlinks));
	                              startActivity(i);} });
	                        dlgAlert.setNegativeButton("Cancel", null);
	                        dlgAlert.create().show();

			}
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

11 Responses

  1. Stacy Williams September 25, 2012 / 3:45 pm

    Thanks for your nice experience to share with us. Really awesome article with plenty of informative things to be known for us.

  2. @prab_bu January 13, 2013 / 10:04 pm

    hi, thanks for ur nice tutorial. btw, how many size of the single of image in pixels that u use?? thanks in advance.

    • Christian January 16, 2013 / 1:05 am

      Hi Prab_bu,

      Thanks for your comment. I am not sure if I understand your question. Are you asking what the sizes are of the images used in the tutorial?

      • @prab_bu January 16, 2013 / 3:02 pm

        yes sir, i’m asking what size of the images? and after i tried your nice tutorial. i wonder is it possible to make an app like this -> let’s say i have a main activity that consist of listview and inside of listview, there are 2 menus. and each of them, consist of 3 sub menus which is a gridview layout, nah my another question is how i link up all of my menus? i’m stucked in linking the first item on listview to gridview menu. thanks for taking your time to read my question sir. i appreciate it so much.

        • Christian January 16, 2013 / 10:03 pm

          Hi Prab bu,

          For the image sizes you can use the references of the different screen sizes and resource folders in your project.

          xlarge screens are at least 960dp x 720dp
          large screens are at least 640dp x 480dp
          normal screens are at least 470dp x 320dp
          small screens are at least 426dp x 320dp

          In case you want 2 images in your grid (horizontally) make 4 images based on the above dimensions and divide the above widths by 2.

          To convert DP to PX you can use this convenient website: http://labs.skinkers.com/content/android_dp_px_calculator/

  3. Amit January 22, 2013 / 4:18 pm

    Mindblowing TutoriaL. helped a lot. Thanks

  4. yogi eka April 24, 2013 / 5:14 am

    thx u for great tutorial!!

  5. pavan May 31, 2013 / 12:16 pm

    Pavan @(pavanh)

    Very nice tutorial with efficent and detailed explaination, you can also check
    this one context menu

  6. Amit July 10, 2013 / 8:24 am

    such a nice post, really much needed, where can i download complete source code?

Leave a Reply to @prab_bu Cancel reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*