Visit Sponsor

Written by 12:51 pm Android

Android GridView Image Gallery – Setup and Complete Example

An image gallery is one of the most common UI patterns in Android apps — whether you’re showing photos from a user’s gallery, a product catalog, or remote image feeds. GridView provides a simple way to display items in a scrollable two-dimensional grid.

In this guide you’ll learn how to build an Android GridView Image Gallery from scratch, including:

  • Grid layout configuration
  • Adapter implementation
  • Image loading with modern libraries
  • Handling item click events

What Is GridView in Android?

GridView is a subclass of AbsListView that displays items in a two-dimensional scrollable grid. Each grid cell holds a view — typically an ImageView when building image galleries.

Key features:

  • Easy layout for fixed-column grids
  • Adapter-based data population
  • Built-in scrolling and recycling patterns

Modern Best Practice: GridView vs RecyclerView

While GridView works well for simple use cases, for production-grade performance and flexibility consider using RecyclerView with GridLayoutManager — it offers better view recycling and extensibility.

This guide uses GridView for simplicity and learning.

Step 1 — Add Layout with GridView

Create layout file activity_main.xml:

<GridView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"/>
  • numColumns="auto_fit" makes the grid adapt to screen width
  • columnWidth="100dp" helps determine how many columns fit horizontally

Step 2 – Prepare the Adapter Layout

Create a layout for individual grid items (e.g., grid_item.xml):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="4dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:scaleType="centerCrop"/>
</FrameLayout>

This defines how each image will appear inside the grid.

Step 3 – Image Resource List

In your Activity class, prepare a list of drawable resource IDs:

int[] images = {
    R.drawable.photo1,
    R.drawable.photo2,
    R.drawable.photo3,
    // … more resources
};

If loading from an external source (URL), you can adapt using image loading libraries such as Glide or Coil.

Step 4 – Create a Custom Adapter

Define a GridAdapter:

public class GridAdapter extends BaseAdapter {

    private final Context context;
    private final int[] images;

    public GridAdapter(Context context, int[] images) {
        this.context = context;
        this.images = images;
    }

    @Override
    public int getCount() {
        return images.length;
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView imageView;

        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(
                GridView.AUTO_FIT, 300));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = (ImageView) convertView;
        }

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

This adapter supplies grid cells with images from the array.

Step 5 – Set Adapter in Activity

In MainActivity.java:

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

GridAdapter adapter = new GridAdapter(this, images);
gridView.setAdapter(adapter);

The gallery is now populated with grid items.

Handling Item Clicks

To respond when users tap an image:

gridView.setOnItemClickListener((parent, view, position, id) -> {
    Toast.makeText(this,
        "Clicked image index: " + position,
        Toast.LENGTH_SHORT).show();
});

You can launch a detail screen or full-screen viewer from here.

Loading Images From URLs (Recommended)

For remote images, use Glide (modern, fast, memory-aware):

dependencies {
    implementation "com.github.bumptech.glide:glide:4.12.0"
}

Update adapter getView():

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView = (ImageView) convertView != null
        ? (ImageView) convertView
        : new ImageView(context);

    Glide.with(context)
         .load(imageUrls[position])
         .placeholder(R.drawable.placeholder)
         .into(imageView);

    return imageView;
}

✔ Handles caching
✔ Smooth scrolling
✔ Automatic bitmap pooling

GridView vs RecyclerView

FeatureGridViewRecyclerView
Layout flexibilityBasicHigh (GridLayoutManager, Staggered)
View recyclingLimitedAdvanced
AnimationsManualEasy with ItemAnimator
Performance for large listsOKBetter

RecyclerView + GridLayoutManager is preferred for large galleries or paging.

Best Practices (Senior Engineering Insight)

✔ Load images off main thread (Glide/Coil/Picasso)
✔ Use consistent aspect ratio for better grid alignment
✔ Use placeholder images for smooth UX
✔ Avoid large bitmaps on UI thread (OOM risks)
✔ Consider caching remote images

These practices help build scalable image galleries.

Full-Screen Image Preview (Optional)

To show a tapped image in full screen:

  1. Launch a new Activity with the image URL or resource
  2. Use shared Activity transitions (optional) for smooth motion

Example launch:

Intent intent = new Intent(this, FullscreenActivity.class);
intent.putExtra("image_res", images[position]);
startActivity(intent);

In FullscreenActivity, receive and display it.

Summary

Building an Android GridView image gallery is straightforward. You:

  • Defined a grid layout
  • Created an adapter with image data
  • Set the adapter on GridView
  • Handled item clicks
  • Optionally loaded remote images using Glide

This pattern powers photo galleries, product catalogs, and visual dashboards in Android apps.

Visited 13 times, 3 visit(s) today
Close