Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Make A Gallery-Like Image Grid Using Native Android

TwitterFacebookRedditLinkedInHacker News

Previously I had written an article regarding how to make a gallery-like image grid using Ionic Framework, but what if we wanted to accomplish the same using the native Android SDK?

In this tutorial we’ll see how to make use of the Android GridView with an image adapter to display remote images from the internet.

Like with all my tutorials, we’ll be using only a terminal and text editor. So no IDE such as Android Studio or Eclipse. From your command prompt or terminal, run the following:

android create project --activity MainActivity --package com.nraboy.imagegrid --path ./ImageGrid --target android-19 --gradle --gradle 0.11.+

You’ll notice in the above command we are creating our project with the intention of using Gradle instead of Apache Ant.

Let’s start with the simple stuff first. In your newly created project, open the src/res/AndroidManifest.xml file and add the internet permission like so:

<uses-permission android:name="android.permission.INTERNET" />

We are doing this because we will be displaying images directly from the internet.

Native Android Image Grid

Above is a picture of what we’re after for this example.

When it comes to designing this application, let’s start with the Android view XML code. Open your project’s src/res/layout/main.xml file and add replace it with the following code:

<?xml version="1.0" encoding="utf-8"?>
<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:columnWidth="115dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

We are creating an Android GridView where each column of the grid will be 115dp in size and have 5dp x 5dp spacing.

A GridView in Android is populated using some form of adapter. In this case we’ll be creating our own custom adapter. Create a src/main/java/com/nraboy/imagegrid/ImageAdapter.java file and add the following code:

package com.nraboy.imagegrid;

import android.app.*;
import android.os.*;
import android.widget.*;
import java.util.*;
import android.graphics.*;
import android.view.*;
import android.content.*;

public class ImageAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Bitmap> bitmapList;

    public ImageAdapter(Context context, ArrayList<Bitmap> bitmapList) {
        this.context = context;
        this.bitmapList = bitmapList;
    }

    public int getCount() {
        return this.bitmapList.size();
    }

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

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

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

        imageView.setImageBitmap(this.bitmapList.get(position));
        return imageView;
    }

}

In the above code we are essentially taking an ArrayList of Bitmap and assigning the content at any given index to a particular cell in the grid. We are lucky enough to have the getView function determine the current view and position. The view being the cell.

This brings us to the MainActivity class we created when building our project from the command line. We’re going to capture the grid from our XML and populate it with images of our choice. Open your src/main/java/com/nraboy/imagegrid/MainActivity.java file and add the following code:

package com.nraboy.imagegrid;

import android.app.Activity;
import android.os.Bundle;
import android.graphics.*;
import java.util.*;
import java.net.*;
import android.widget.*;

public class MainActivity extends Activity {

    private GridView imageGrid;
    private ArrayList<Bitmap> bitmapList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.imageGrid = (GridView) findViewById(R.id.gridview);
        this.bitmapList = new ArrayList<Bitmap>();

        this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));

    }

}

Wait a second! How are we going to get our images in there? We are assigning our custom adapter to the grid, but there are no images in the ArrayList. In this particular example we’re going to be loading our images directly from the internet. You can choose to load bitmap images however you wish.

private Bitmap urlImageToBitmap(String imageUrl) throws Exception {
    Bitmap result = null;
    URL url = new URL(imageUrl);
    if(url != null) {
        result = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    }
    return result;
}

The above function will take a remote image from URL and load it as a bitmap. So all together in our MainActivity class, we have the following:

package com.nraboy.imagegrid;

import android.app.Activity;
import android.os.Bundle;
import android.graphics.*;
import java.util.*;
import java.net.*;
import android.widget.*;

public class MainActivity extends Activity {

    private GridView imageGrid;
    private ArrayList<Bitmap> bitmapList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.imageGrid = (GridView) findViewById(R.id.gridview);
        this.bitmapList = new ArrayList<Bitmap>();

        try {
            for(int i = 0; i < 10; i++) {
                this.bitmapList.add(urlImageToBitmap("http://placehold.it/150x150"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));

    }

    private Bitmap urlImageToBitmap(String imageUrl) throws Exception {
        Bitmap result = null;
        URL url = new URL(imageUrl);
        if(url != null) {
            result = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        }
        return result;
    }

}

I’ve chosen just to load ten generic placeholder images in the above code.

To build this, from your terminal or command prompt, run the following Gradle command:

./gradlew assemble

You should have a ImageGrid-debug.apk file generated in the build/output/apk directory.

Conclusion

It is not too difficult to create a grid of images using native Android. If you’ve been keeping up with my tutorials, you’ve now seen the native Android method, as well as the hybrid method with Ionic Framework. We populated our grid of images using remote images from the internet loaded into bitmap form.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.