Building a photo gallery with GridView on Android
Scroll through a phone's camera roll and the grid announces itself immediately: rows of square thumbnails that respond instantly to your thumb. Reproducing that behaviour in your own app takes more than dropping an ImageView into a layout. You need a data source, an adapter that recycles rows, thumbnails decoded at a sensible size, and touch handling that opens the full picture. This tutorial builds that pipeline step by step, using GridView because its rules are easy to see.
GridView was among the earliest list components in Android, and it still earns its place in tutorials and in production apps that predate the material design era. Because it recycles children for you, it is a good teacher: you can trace where the data flows without a wall of framework classes standing in the way. Once the mechanics make sense, porting the same gallery to RecyclerView becomes a small change rather than a rewrite.
The finished screen lists every image the device's media store knows about, draws a cropped square thumbnail for each one, and opens a full-screen viewer when you tap it. Along the way we cover permissions that changed in Android 13, bitmap sampling, cache sizing, and the orientation metadata that leaves an otherwise handsome grid sideways. The code is written in Kotlin and fits inside Android Studio's empty activity template.
You will need a handset or emulator with a populated gallery — a morning at Bondi Beach or an afternoon through Melbourne's laneways fills one fast — plus Android Studio Hedgehog or newer. If you are reading this on the train between Sydney and Canberra, pull the project down before departure, because the scoped storage behaviour we depend on is painful to debug over a congested mobile connection.
Setting up the project and finding the images
Create a new project with an empty views activity, set the language to Kotlin, and keep the generated XML layouts. GridView lives in the classic view system, so there is nothing to configure in the build file beyond a sensible minSdk value, around 21 if you want to support older budget handsets still common in second-hand Australian marketplaces.
Permissions are where most first attempts stall. On Android 13 and above, request READ_MEDIA_IMAGES; below that, READ_EXTERNAL_STORAGE with a maxSdkVersion of 32 covers older releases. Ask at runtime with a rationale dialog, and handle the denial path gracefully — a gallery that shows an empty screen with no explanation reads like a broken app.
Once permission is granted, query MediaStore.Images.Media against EXTERNAL_CONTENT_URI. Pull the _ID, DISPLAY_NAME, DATE_ADDED, WIDTH and HEIGHT columns, and sort by DATE_ADDED descending so the newest shot appears first. Content URIs rather than file paths keep the query working under scoped storage.
Designing the grid and its spacing
A GridView needs a column count, and hard-coding four looks wrong on a small phone and wasteful on a tablet. Divide the measured width by a target cell of roughly 120dp, set that as numColumns, and pair it with stretchMode="columnWidth" so cells share the leftover space evenly.
Each cell holds a single ImageView with scaleType="centerCrop" and adjustViewBounds="false", which forces a consistent square regardless of the original aspect ratio. Gutters come from a small margin inside the item layout rather than from padding on the GridView itself, so the outer edge of the grid stays flush with the screen.
Column counts change with orientation and screen size, so derive them from a dimension resource with a values-sw600dp override for large tablets. Recomputing on rotation is straightforward; letting the layout manager handle the rest is even better once you migrate.
Decoding thumbnails and keeping memory in check
Loading the original bitmap into every cell will exhaust memory within seconds. On API 29 and newer, ContentResolver.loadThumbnail() returns a correctly sized preview directly. On older devices, request the thumbnail URI from MediaStore.Images.Thumbnails and decode it with an inSampleSize calculation tied to the cell dimensions.
Decode off the main thread — a suspend function inside a lifecycleScope works well — then publish the result to the adapter. Pair that with an LruCache sized to a fraction of ActivityManager.getMemoryClass(), and the grid stays smooth while scrolling through thousands of images.
While a thumbnail resolves, a placeholder keeps the cell from collapsing. If you want something more eye-catching, this ImageView blink animation demo shows the technique, although a gentle cross-fade usually reads better in a dense grid of squares. Remember to clear the cache in onTrimMemory and to recycle bitmaps when the activity is destroyed.
Weighing GridView against RecyclerView
The choice between the two list components comes down to how much control you want over recycling, spacing and animation.
| Consideration | GridView | RecyclerView |
|---|---|---|
| Recycling | Built in, but holds all children | Scoped and position aware |
| Layout flexibility | Fixed column count with stretch modes | Pluggable layout managers, lists and grids |
| Spacing | Margins set inside the adapter | ItemDecoration and span spacing |
| Animation | Basic fades and simple transitions | ItemAnimator plus shared element transitions |
| Setup effort | Very little code | More classes, far more control |
| Best fit | Small, stable galleries | Large libraries with frequent updates |
GridView wins on brevity. You instantiate it, hand it an adapter, and it does the rest, which makes it ideal for a tutorial and for an app whose gallery rarely changes while the user scrolls.
RecyclerView wins when the list grows, when items need headers, or when you want staggered layouts. The concepts transfer directly: what was getView() becomes onCreateViewHolder(), and the recycling logic moves into the holder rather than the parent.
Handling taps and touch input
Wire an OnItemClickListener that reads the adapter position, fetches the corresponding image id, and starts a detail activity with that id as an intent extra. Passing an identifier rather than a bitmap keeps the intent small enough to survive the transaction limit on older versions.
Touch targets need at least 48dp of usable height, and each thumbnail should carry a content description for screen readers. Developers arriving from desktop code sometimes reach for pointer APIs they remember, such as SetCursorPos explained, but Android delivers touch input through MotionEvent and lets the view hierarchy consume it.
In the detail screen, add pinch-to-zoom with ScaleGestureDetector, then dismiss on a tap outside the image. Preserve the scroll position of the grid across rotation by storing the first visible position in the saved instance state.
Copyright, privacy and Australian expectations
Photographs carry legal ownership. Under the Copyright Act 1968, the photographer usually owns the copyright in their image, so a gallery that republishes pictures from other sources needs a licence and, for Creative Commons material, visible attribution. Preserve the artist metadata in bundled samples rather than flattening everything into anonymous drawables.
Privacy matters just as much. The Privacy Act 1988 and the Australian Privacy Principles apply when your app collects telemetry or personal information, and Google Play requires a data safety declaration that lists photo access explicitly. Location tags inside EXIF can reveal a home address, so offer a switch that strips GPS coordinates before images are shared from the app.
The local market rewards care. Australian camera retailers such as Camerahouse and Mitchell's Camera Centre in Adelaide sell lenses and bodies priced in dollars with 10% GST, and buyers there expect sample images to match the real product. Upload your own photographs rather than licensing distant stock. Finally, Australian mobile plans carry generous but finite data allowances, so cache thumbnails on the handset instead of refetching them over a Telstra connection each time the grid opens.
Recommendations for a reliable release
A short checklist catches most problems before they reach users.
- Query
MediaStorefor thumbnails rather than decoding original files yourself. - Sample every bitmap to the cell size and hold decoded results in an
LruCache. - Move disk and bitmap work off the main thread using coroutines.
- Read and honour EXIF orientation so no photo appears rotated.
- Provide a placeholder image and a meaningful content description per cell.
- Test on a low-end device with a modest screen, not only on a flagship handset.
- Watch cold-start time and frame drops with the profiler before publishing.
Apply these in the order they appear and the gallery will behave like the camera roll on any phone. Ship it with a small sample set first, watch how the adapter behaves with a few thousand images, and let the profiler decide whether GridView is still the right tool for the job.