Main navigation

Android Gridview Tutorial using Android Gridlayout Example

adsense

Creating a New Project – Android Gridview

  1. Open Android Studio and create a new project AndroidGridview and company domain application.example.com (We have used our own company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose Min SDK, we have kept the default value. Again Click Next and Choose Blank Activity .
  3. Choose the Activity as MainActivity and click next.
  4. Leave all other things as default and Click Finish.

A new project will be created and gradle will resolve all the dependencies.

Download full code here:

Android GridView Tutorial

Difference between Android GridView and Gridlayout

Android GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you’d want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen.

Whereas a GridLayout is a just a layout that places its children in a rectangular grid. The basic difference is between Android GridView and Gridlayout is that gridView is scrollable listView but GridLayout is just a layout which can be either scrolled or not according to code in MainActivity.

In this tutorial, we will take android gridlayout example to make Android GridView. First we will generate the layout of Android GridView and then will go for MainActivity.

Android GridLayout Example

Layout of android gridview will be generated through android gridlayout. Create a new resource layout file at path: /home/navneet/AndroidStudioProjects/AndroidGridView/app/src/main/res/layout named android_gridlayout.xml:

android_gridlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="https://schemas.android.com/apk/res/android"
          android:id="@+id/grid_view"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:numColumns="auto_fit"
          android:columnWidth="90dp"
          android:horizontalSpacing="10dp"
          android:verticalSpacing="10dp"
          android:gravity="center"
          android:stretchMode="columnWidth" >

</GridView>

As you could see above code is an android gridlayout example. Attributes inside layout are pretty much self explanatory. Still if you have any doubt then comment below.

Now we have to show images in gridView. So we have first insert images in drawables folder. Include 7-8 images at path …/AndroidGridView/app/src/main/res/drawable . We would suggest you to download below images and paste it inside drawable folder:

Android GridView Images

Now we will move on to making custom Adapter.

Android GridView Custom Adapter

Create a new class named ImageAdapter.java at path …/AndroidGridView/app/src/main/java/com/androidtutorialpoint/androidgridview (This is same path where MainActivity.java is stored) and add following code:

ImageAdapter.java

package com.androidtutorialpoint.androidgridview;

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;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return mThumbIds[position];
    }

    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) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(370, 370));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    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
    };
}

First, this implements some required methods inherited from BaseAdapter. getItem(int) and getItemId(int) are not needed here so returning null.
The first method necessary is getView(). This method creates a new View for each image added to the ImageAdapter. When this is called, a View is passed in, which is normally a recycled object, so there is a check to see if the object is null. If it is null, an ImageView is created and configured with required properties for the image presentation as described below:

  1. setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View. This ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate.
  2. setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center (if necessary).
  3. setPadding(int, int, int, int) defines the padding for all sides. (Note that, if the images have different aspect-ratios, then less padding will cause more cropping of the image if it does not match the dimensions given to the ImageView.)

If the View passed to getView() is not null, then the local ImageView is initialized with the recycled View object.
At the end of the getView() method, the position integer passed into the method is used to select an image from the mThumbIds array, which is set as the image resource for the ImageView. All that’s left is to define the mThumbIds array of drawable resources. For more information refer Developer Guide for Grid View

Now let’s move to the final part and that is MainActivity.java.

Capturing Android GridView in MainActivity

Insert following code in MainActivity.java:

MainActivity.java

package com.androidtutorialpoint.androidgridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android_gridlayout);

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

        // Instance of ImageAdapter Class
        gridView.setAdapter(new ImageAdapter(this));
    }
}

In the above code, Android GridView is captured from layout using findViewById. Then <>setAdapter<> is used as a custom adapter to source all images to be displayed in GridView.

Run this App. You will see following screen:

Android GridView Tutorial

You can also scroll through images as shown in demo video at start of tutorial.

Showing selected Image on Full Screen

Now we will add one more functionality in this App. Whenever a user selects a particular image then it will be displayed on full screen of smartphone. For this we need to add a listener in MainActivity and initiate a new Activity whenever a new photo is selected. Also we have to create a new xml file. Create a new new xml file named selected_image.xml:

selected_image.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <ImageView android:id="@+id/full_image_view"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
 
</LinearLayout>

Create a new class named FullScreenImage.java. This should be created at same path of MainActivity.java.

FullScreenImage.java

package com.androidtutorialpoint.androidgridview;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

public class FullScreenImage extends AppCompatActivity {

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

        // 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.full_image_view);
        imageView.setImageResource(imageAdapter.mThumbIds[position]);
    }
}

Now we will make few changes in MainActivity.java to pass image id to second Activity i.e. FullScreenImage whenever a user clicks on image.

MainActivity.java

package com.androidtutorialpoint.androidgridview;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android_gridlayout);

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

        // Instance of ImageAdapter Class
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                Toast.makeText(MainActivity.this, "" + position,
                        Toast.LENGTH_SHORT).show();
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getApplicationContext(), FullScreenImage.class);
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }
}

In the above code, we have added a listener that will call onItemClick for image click. So as soon as image is clicked, information will be passed to second activity through Intent.

In the final step we will initiate FullScreenImage Activity. Make following changes in AndroidManifest.xml:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.androidgridview"
          xmlns:android="https://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- FullScreenImage -->
        <activity android:name=".FullScreenImage"></activity>
    </application>

</manifest>

Run this App. You will see following screen. On clicking on an image you will see it in full screen. For example on clicking 9th pic in first image below then second will appear (Here 8 is displayed as Toast message that implies 8th numbered image in array of 0-8).

Android GridView TutorialAndroid GridView Tutorial

So finally our Android Gridlayout Example is complete. You can also refer demo of Android GridView Tutorial given at the start of tutorial.




What’s Next ??

You can see our other tutorials on material design like Android ScrollView, ViewPager and Expandable ListView Tutorials etc.

We hope you liked our Android GridView Tutorial, please leave comments in the comment section below in the case of any doubts. Let us know how do you liked this Android Spinner Tutorial.

To download the full code for the Android GridView Tutorial, Click on the Download Now link below.

Android GridView Tutorial


Reader Interactions

Leave a Reply

Advertisment ad adsense adlogger