Android Grid View

Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined  but they automatically inserted to the layout using a ListAdapter
An adapter  actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
Following are the important attributes specific to GridView −
android:id
This is the ID which uniquely identifies the layout.
android:columnWidth
This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.
android:gravity
Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.
android:horizontalSpacing
Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm.
android:numColumns
Defines how many columns to show. May be an integer value, such as "100" or auto_fit which means display as many columns as possible to fill the available space.
android:stretchMode
Defines how columns should stretch to fill the available empty space, if any. This must be either of the values −
none − Stretching is disabled.
none − Stretching is disabled.
spacingWidth − The spacing between each column is stretched.
spacingWidth − The spacing between each column is stretched.
columnWidth − Each column is stretched equally.
columnWidth − Each column is stretched equally.
spacingWidthUniform − The spacing between each column is uniformly stretched..
spacingWidthUniform − The spacing between each column is uniformly stretched..
android:verticalSpacing
Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm.
This example will take you through simple steps to show how to create your own Android application using GridView. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      GridView gridview = (GridView) findViewById(R.id.gridview);
      gridview.setAdapter(new ImageAdapter(this));
   }
}
Following will be the content of res/layout/activity_main.xml file −
<?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="90dp"
   android:numColumns="auto_fit"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
/>
Following will be the content of  res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">HelloWorld</string>
   <string name="action_settings">Settings</string>
</resources>
Following will be the content of src/com.example.helloworld/ImageAdapter.java file −
package com.example.helloworld;

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 mContext;
   
   // Constructor
   public ImageAdapter(Context c) {
      mContext = c;
   }
   
   public int getCount() {
      return mThumbIds.length;
   }

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

   public long getItemId(int position) {
      return 0;
   }
   
   // create a new ImageView for each item referenced by the Adapter
   public View getView(int position, View convertView, ViewGroup parent) {
      ImageView imageView;
      
      if (convertView == null) {
         imageView = new ImageView(mContext);
         imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
         imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         imageView.setPadding(8, 8, 8, 8);
      } 
      else 
      {
         imageView = (ImageView) convertView;
      }
      imageView.setImageResource(mThumbIds[position]);
      return imageView;
   }
   
   // Keep all Images in array
   public Integer[] mThumbIds = {
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7,
      R.drawable.sample_0, R.drawable.sample_1,
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7,
      R.drawable.sample_0, R.drawable.sample_1,
      R.drawable.sample_2, R.drawable.sample_3,
      R.drawable.sample_4, R.drawable.sample_5,
      R.drawable.sample_6, R.drawable.sample_7
   };
}
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run  icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Let's extend the functionality of above example where we will show selected grid image in full screen. To achieve this we need to introduce a new activity. Just keep in mind for any activity we need perform all the steps like we have to implement an activity class, define that activity in  AndroidManifest.xml file, define related layout and finally link that sub-activity with the main activity by it in the main activity class. So let's follow the steps to modify above example −
Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file can include each of the fundamental life cycle methods.
package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

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
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      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){
            // Send intent to SingleViewActivity 
            Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
            // Pass image index
            i.putExtra("id", position);
            startActivity(i);
         }
      });
   }
}
Following will be the content of new activity file src/com.example.helloworld/SingleViewActivity.java file −
package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class SingleViewActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.single_view);
      
      // Get intent data
      Intent i = getIntent();
      
      // Selected image id
      int position = i.getExtras().getInt("id");
      ImageAdapter imageAdapter = new ImageAdapter(this);
      
      ImageView imageView = (ImageView) findViewById(R.id.SingleView);
      imageView.setImageResource(imageAdapter.mThumbIds[position]);
   }
}
Following will be the content of res/layout/single_view.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >
   
<ImageView android:id="@+id/SingleView"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"/>
 
</LinearLayout>
Following will be the content of  AndroidManifest.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.helloworld">
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.helloworld.MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
   
      <activity android:name=".SingleViewActivity"></activity>
   
   </application>
</manifest>
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run  icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now if you click on either of the images it will be displayed as a single image, for example−

    46 Lectures 
     7.5 hours 

 Aditya Dua

    32 Lectures 
     3.5 hours 

 Sharad Kumar

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page