Posted by : Unknown Tuesday, August 20, 2013



Hello everyone! For this post, I am going to keep working with the different layouts. On my previous post, I tried out the List View layout. Now, I am going to work with the layout called Grid View. I am going to create a new Android application project named GridViewDemo. I will use it to learn about the Grid View layout by creating a grid of images. This will be the result:


GridViewDemo Application


The class GridView is one of the subclasses of the class ViewGroup found in the package android.view. The package provides classes for the user interface which includes screen layouts and ways for the user to interact with them. The user interface that you design can have more than one layout nested within another layout.

The Grid View layout is similar to the List View layout. The List View layout displays a list of scrollable objects and the objects are inserted to the list using an Adapter. The Grid View layout displays objects in a two-dimensional, scrollable grid and the objects are inserted to the layout using a ListAdapter. The interface ListAdapter implements Adapter. The ListAdapter class is used as a bridge between the ListView layout and the data source. The ListView is able to display the data source wrapped in a ListAdapter.

First, create the new Android application project named GridViewDemo. Go to File in the main menu and select New -> Other. The wizard will start. Select Android Application Project found in the Android folder and click Next.


Eclipse New Android Application Project


In the New Android Application window, I filled it out with the following fields and clicked Next:

  •      Application Name: GridViewDemo
  •      Project Name: GridViewDemo
  •      Package Name: com.android.gridviewdemo
  •      Minimum Required SDK: API 14: Android 4.0 (IceCreamSandwich)
  •      Target SDK: API 17: Android 4.2 (Jelly Bean)
  •      Compile With: API 18: Android 4.3
  •      Theme: Holo Light with Dark Action Bar

In the following window, select the checkboxes to create a custom launcher icon, to create an activity, and to create project in workspace. Configure the launcher icon any way you like. For my launcher icon, I chose the following and clicked Next:

  •      Foreground: Image – launcher_icon
  •      Selected Trim Surrounding Blank Space checkbox
  •      Additional Padding: 12%
  •      Foreground Scaling: Crop
  •      Shape: Square
  •      Background Color: Blue

Eclipse Configure Launcher Icon

In the next window, select the checkbox to create an activity and select Blank Activity. Click Next. In the Blank Activity window, I left the default values which are:


  •      Activity Name: MainActivity
  •      Layout Name: activity_main
  •      Navigation Type: None


Click Finish and wait for Eclipse to create the project. After Eclipse is done, you can see the project GridViewDemo in the Project Explorer and the file activity_main.xml opened in the Graphical Layout.

activity_main.xml - Graphical Layout

As you can see, the application is displaying the string “Hello world!” and the file activity_main.xml looks like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

I want to create a grid of images. To do this, first save the images you would like to display in the grid into the folder drawable-hdpi found under the res folder. Modify the activity_main.xml to:

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="150dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:gravity="center"
    tools:context=".MainActivity" >

</GridView>

As you can see, I added a new id named grid_view. I set the width of each column to 150dp. This dimension value can vary depending on what size you want to display your images. In my case, a width of 100dp will display three columns while a width of 150dp will display two columns. The attribute android:numColumns will set how many columns to show and the attribute android:stretchMode will set how columns should stretch to fill the available empty space. There are also the attributes android:horizontalSpacing and android:verticalSpacing which set the spacing between columns and rows respectively.

Next, create a new class by right clicking the src folder and select New->Class. The new class will be named ImageAdapter and it will extend BaseAdapter. 

Eclipse New Java Class


It will have the following code:

package com.android.gridviewdemo;

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 ImageAdapter extends BaseAdapter{
      
       private Context context;

       private Integer[] images = {R.drawable.pic_1,
                                   R.drawable.pic_2,
                                   R.drawable.pic_3,
                                   R.drawable.pic_4,
                                   R.drawable.pic_5,
                                   R.drawable.pic_6,
                                   R.drawable.pic_7,
                                   R.drawable.pic_8,
                                   R.drawable.pic_9,
                                   R.drawable.pic_10};
      
       public ImageAdapter(Context context){
              this.context = context;
       }
      
       public int getCount() {
              return images.length;
       }

       public Object getItem(int position) {
              return images[position];
       }

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

       public View getView(int position, View convertView, ViewGroup                                parent) 
       {
              ImageView imageView;
             
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(130, 130));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(15, 15, 15, 15);
        } else {
            imageView = (ImageView) convertView;
        }

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

As you can see, an Integer array holds all the references to the images. The names of my images are pic_1, pic_2, etc. Replace those strings to the name of your images. The class ImageAdapter extends BaseAdapter which means we will need to implement the methods from BaseAdapter, which are getCount(), getItem(), getItemId(), and getView(). The method getCount() returns the length of the images array, which is the number of image references you add. The method getItem(int position) returns the object associated with that position in the images array. The method getItemId(int position) returns a long associated to the id. The method getView(int position, View convertView, ViewGroup parent)  returns a View associated to the data at the specified position. This method creates a new View for each image added to the ImageAdapter. 

First, the specified View is checked if it is null. If the View is null, a new View object is declared and given properties with methods setLayoutParams(), setScaleType(), and setPadding(). The method setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View. The method setScaleType(ImageView.ScaleType.CENTER_CROP) sets the images to be cropped toward the center. The method setPadding(int, int, int, int) sets the padding for all sides. If the specified View is not null, then the local ImageView object is initialized with the recycled View object. With the method setImageResource(int), the image reference in the array is set as the image resource for the ImageView.

Next, modify the Main_Activity.java file found on the src folder by adding the following code on the onCreate method:

GridView gridview = (GridView) findViewById(R.id.grid_view);
gridview.setAdapter(new ImageAdapter(this));

gridview.setOnItemClickListener(new OnItemClickListener() {
               public void onItemClick(AdapterView<?> parent, View v,                                          int position, long id) {
                   Toast.makeText(getApplicationContext(), "" +                                           position, Toast.LENGTH_LONG).show();
               }
});


A GridView object is initialized using the id named grid_view added earlier on the activity_main.xml file. Then, the method setAdapter() is used to set a custom adapter which is the adapter created earlier named ImageAdapter. With the method setOnItemClickListener(), a new Adapterview.OnItemClickListener is passed as parameter. With the method onItemClick(), a Toast is displayed with the message of the position of the image when the user clicks on it. The position count starts at zero.

To test the application, right click the project folder on the Project Explorer and select Run As->Android Application. Wait for Eclipse to launch the application. It might take a while if you are starting the emulator. 


GridViewDemo in Emulator

Thank you for reading. Feel free to leave comments, subscribe, or follow me on Google+.







{ 3 comments... read them below or Comment }

  1. how do you set only four images at center like

    * *
    * *
    set * as images

    ReplyDelete
  2. how do you set your images at the middle using landscape orientation
    ex. four images(*)

    * *
    * *
    please help

    ReplyDelete
    Replies
    1. Use android:paddingTop, paddingLeft, paddingRight, paddingBottom to specify the images are in the center and numColumns to specify you want 2 columns.

      Delete

      

Followers

Powered by Blogger.

Translate

Google Search

Support Blog

- Copyright © Learning Android Development -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -