Recipe 3.9 Displaying Images Using the GridView

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
Grid.zip

The GridView shows items in a two-dimensional scrolling grid. You can use the GridView together with an ImageView to display a series of images. The following recipe demonstrates how.

Solution

Like the previous recipe, this example assumes you have a series of images in the res/drawable-mdpi folder (see Figure 3-21).

To use the GridView, add the <GridView> element to your UI, such as the activity_main.xml file, as follows:

<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" >
    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" />

</RelativeLayout>

Code the activity as follows:

package net.learn2develop.grid;

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.AdapterView.OnItemClickListener; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.