Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Implementing GridView in Android

In this article we will see how to create a gridview of ImageViews within a LinearLayout. We will also have an Exit ImageButton and we will put a picture as our screen background.

What is GridView in android?

GridView is a layout used in android to display items in a grid. It is a ViewGroup. For a GridView we use an adapter to automatically insert items into the layout

GridView

Figure 1: GridView

In this tutorial

For this tutorial I will show you how to create a gridview of ImageViews within a LinearLayout. I will also have an Exit ImageButton and we will put a picture as our screen background.

Coding the application

Create a new Android Project in Eclipse and name it Application4. Name the main activity ApplicationActivity4.

Project Structure

Figure 2: Project Structure

Step 1:

As seen from the project structure above I have three images in the drawable-hdpi folder. For this tutorial you will have to obtain 2 extra images. The ic_launcher.png image will already be in the folder. You will need a mars.png image and a ufo1.png image. I used a ufo1.png 88 x 88 pixels. Save the images as .png and put them in drawable-hdpi folder. Note for beginners: If you have trouble finding your folders to save these images, an easy way to put the images in that folder is to copy them from where you have them saved then right click on the drawable-hdpi folder in the Eclipse folder structure as seen above and select paste.

Step 2:

Copy and paste this code into your string.xml file(located in the values folder within the res folder):

Listing 1: string.xml code

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

    <string name="hello"><u>Grid View</u></string>
    <string name="app_name">Application4</string>

</resources>

Step 3:

Copy and paste this code into your main.xml file:

Listing 2: main.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/mars" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:gravity="center"
        android:textColor="#23B52F"
        android:textSize="36sp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="(Click UFO to exit)"
        android:layout_gravity="center"
        android:textColor="#000000"
        android:textSize="18sp" />

    <ImageButton
        android:id="@+id/ufo1"
        android:layout_width="66dp"
        android:layout_height="72dp"
        android:src="@drawable/ufo1"
        android:layout_gravity="center" />
    
     <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:numColumns="auto_fit"
		android:verticalSpacing="8dp"
		android:horizontalSpacing="8dp"
		android:columnWidth="70dp"
		android:stretchMode="columnWidth"
		android:gravity="center"
	/>

</LinearLayout>

Notice here I put the GridView within the LinearLayout (inside the LinearLayout tags in other words). Notice LinearLayout’s background is android:background="@drawable/mars" and the ImageButton drawable is set to ufo1 android:src="@drawable/ufo1". Notice our GridView’s width and height is set to fill_parent. Also numColumns is set to auto_fit. Note vertical spacing, horizontal spoacing, column width, stretch mode and gravity.

You’ll end up with this in the Graphical Layout:

Graphical Layout

Figure 3: Graphical Layout

Step 4:

Copy and paste this code into Application4Activity (i,e, your main activity). Remember not to copy over your package name at the top of your file.

Listing 4: Application4Activity code

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Application4Activity extends Activity {
	 //---the images to display---
    Integer[] imageIDs = {
    		
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher, 
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher
    };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final ImageButton ufo1 = (ImageButton) findViewById(R.id.ufo1);
        ufo1.setBackgroundColor(color.transparent);

        ufo1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	
            	finish();
            }
        });
        
        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
        public void onItemClick(AdapterView<?> parent,
        View v, int position, long id)
        {
        Toast.makeText(getBaseContext(),
       "pic" + (position + 1) +" selected",
        Toast.LENGTH_SHORT).show();
        }
        });
        }
        public class ImageAdapter extends BaseAdapter
        {
        private Context context;
        public ImageAdapter(Context c)
        {
        context = c;
        }
        //---returns the number of images---
        public int getCount() {
        return imageIDs.length;
        }
        //---returns the ID of an item---
        public Object getItem(int position) {
        return position;
        }
        //---returns the ID of an item---
        public long getItemId(int position) {
        return position;
        }
        //---returns an ImageView view---
        public View getView(int position, View convertView,
        		
        		ViewGroup parent)
        {
        ImageView imageView;
        if (convertView == null) {
        imageView = new ImageView(context);
        imageView.setLayoutParams(new
        GridView.LayoutParams(80, 80));
        imageView.setScaleType(
        ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(4, 4, 4, 4);
        } else {
        imageView = (ImageView) convertView;
        }
        imageView.setImageResource(imageIDs[position]);
        return imageView;
        }
               
    }
}

Step 5:

Once you have pasted in everything it’s time to run your project. You will get something like this:

Application running.

Figure 4: Application running.

The GridView is scrollable and the UFO is an Exit ImageButton.

Code Breakdown

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

Take note of the imports used. Eclipse lets you know if you need certain imports anyway so I wouldn’t worry too much about it. Notice how we define our array of images:

Integer[] imageIDs = {
    		
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher, 
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher
    };

We declare our GridView and use the setAdapter() method which then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. We then set an item click listener and display a toast message once the item is clicked.

GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
        public void onItemClick(AdapterView<?> parent,
        View v, int position, long id)
        {
        Toast.makeText(getBaseContext(),
       "pic" + (position + 1) +" selected",
        Toast.LENGTH_SHORT).show();
        }
        });

Next we create a class ImageAdapter that extends BaseAdapter. Inheritance is used here. See http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html for an explanation of inheritance. The site referenced above is great for reference in relation to java concepts etc. The ImageAdapter class is created here, notice the constructor (see http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html if you’d like to know more about constructors).

public class ImageAdapter extends BaseAdapter
        {
        private Context context;
        public ImageAdapter(Context c)
        {
        context = c;
        }
        {
<p>Take note of the methods used and what they return: </p>
//---returns the number of images---
        public int getCount() {
        return imageIDs.length;
        }
        //---returns the ID of an item---
        public Object getItem(int position) {
        return position;
        }
        //---returns the ID of an item---
        public long getItemId(int position) {
        return position;
        }
        //---returns an ImageView view---
        public View getView(int position, View convertView,
        		
        		ViewGroup parent)
        {

Next the getView() method creates a new View for each image added to the ImageAdapter. A view is passed in when this is called. This is usually a recycled object. If the object is null, an ImageView is instantiated and given the properties we set. Note how we set the properties for an image (imageView.setLayoutParams etc.).

 public View getView(int position, View convertView,
        		
        		ViewGroup parent)
        {
        ImageView imageView;
        if (convertView == null) {

        imageView = new ImageView(context);
        imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(4, 4, 4, 4);

        } else {

        imageView = (ImageView) convertView;

        }

        imageView.setImageResource(imageIDs[position]);
        return imageView;
       
 }

ImageView is initialised with the recycled View Object if the View passed to getView() is not null. The position passed into the View() method is then used to select an image from the imageIDs array and the ImageView is then designated/set with that image:

imageView.setImageResource(imageIDs[position])
return imageView;

Conclusion

From this tutorial you should now have an understanding of how to display images in a GridView and how to put a layout in another layout. I hope you learned something from this tutorial. If you enjoyed or liked this tutorial leave me a like. Thanks very much. See you next time, Steve.



Has designed and developed several android applications from scratch which are available on Google Play.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login