Android GridView Tutorial With Example For Beginners

Welcome to Android GridView Tutorial With Example For Beginners.

GridView is a view group that displays the items in the two dimensional view. (Row and Column)

This grid view items are vertically scrollable but not horizontally.

GridView is the dynamical view, meaning that it inserts the data item automatically using the adapter.

Android gridview can adjust any number of data items with it’s scrollable feature.

Most common example of gridview is your android device’s gallery application.

Gallery displays the images and videos in a gridview with rows and columns.

Gridview also enable user to click on it’s any item. We will also learn how to deal with click event.

Adapter of GridView

Adapter will work as an agent between gridview and the data source.

It will fetch the data items one by one from the data source and passes it to the gridview.

GridView will create it’s cell using this data item.

Adapter is the simple JAVA class. We can make custom adapter by extending the ArrayAdapter or Base adapter.

We will see the usage of adapter in the example that we will create at the end of this article.

GridView XML Code

Following is the XML representation of the android gridview.

XML representation of grid view has various properties.

Let us see how this properties affects the gridview settings.

1. android:id=”@+id/gv”

id is the unique identity for the gridview.

In the java file, compiler will get the reference to gridview using this id.

Value of ID should be unique in the whole android app to reduce the runtime errors.

2. android:layout_width

It defines the actual width of the gridview.

Generally, it should be match_parent which means a full width gridview.

However, you can give specific value in dp in certain cases.

3. android:layout_height

This property gives the height to the gridview.

For making our gridview a responsive through various screen size, you can give it a full height or you can define weight with linearlayout.

For specific purpose, you can also define it in the dp values to make static height in any screen size.

4. android:numColumns=”3″

This property tells the grid view how many columns it need to create.

Two types of value can be there.

One is auto_fit and another is any integer number.

auto_fit means that gridview will decide itself how many columns to create according to the width of the android device.

Specific integer number is static and number of columns will be of this value regardless of screen width.

5. android:horizontalSpacing=”3dp”

It defines the default horizontal space amount among every columns.

The value of this property can be in pixel(px),density pixel(dp) or scale independent pixel(sp).

6. android:verticalSpacing=”6dp”

It defines the default vertical space amount among every rows.

The value of this property can be in pixel(px),density pixel(dp) or scale independent pixel(sp).

7. android:columnWidth=”30dp”

This property is giving the fixed width to the every column of the gridview.

8. android:gravity=”center”

It specifies the gravity within each cell.

Methods of GridView

Android gives us specific methods to control the gridview.

1. setAdapter(ListAdapter adapter)

It simply attach the adapter to the grid view.

2. setColumnWidth(int columnWidth)

It sets the column width programmatically.

3. setHorizontalSpacing(int horizontalSpacing)

Set the amount of horizontal (x) spacing to place between each item in the gridview.

4. setNumColumns(int numColumns)

Set the number of columns in the gridview.

5. setSelection(int position)

Sets the currently selected item

6. setVerticalSpacing(int verticalSpacing)

Set the amount of vertical (y) spacing to place between each item in the gridview.

7. getColumnWidth()

Return the width of a column in the grid.

8. getGravity()

Describes how the child views are horizontally aligned.

9. getHorizontalSpacing()

Returns the amount of horizontal spacing currently used between each item in the grid.

10. getNumColumns()

Get the number of columns in the grid.

11. getVerticalSpacing()

Returns the amount of vertical spacing between each item in the gridview.

GridView Android Studio Examples

Now let us make two gridview projects.

In the first one, we will use base adapter and in another, we will use array adapter.

Step 1. Layout Work

First of all, we will make a gridview using base adapter.

Create a new project in android studio.

I recommend you to select empty activity when making a new project.

Now in the activity_main.xml file, add the following code

Main layout contains one gridview.

This gridview will have three columns.

Now prepare a new XML layout file in res->layout directory.

Give this file a name like grid_item.xml

Code structure for grid_item.xml is as the following

This file creates the layout for the cell of the grid view.

Adapter will use this file when creating a cell with data items.

One imageview and one textview is there in this file.

Now let us add some car images in our project.

Download these images by clicking on the below link.

Download Our car_images_listview

After downloading these images, copy them into the res->drawable directory.

Step 2. Grid Model

Let us create a model class for grid view.

This model will help us to maintain the data seamlessly.

Make a new JAVA class and give it a name ImageModel.java

Write down the following coding lines in ImageModel.java

Above model class has two main variables.

One is the string variable and another is integer variable.

String is for image name and another is integer reference to drawable image.

Now for both these variables, I have written getter and setter methods.

Step 3. Adapter Creation

Make a new JAVA class called GridBaseAdapter.java

Code structure for GridBaseAdapter.java should look like the below

You can see that the above class is extending the Base adapter.

So we have override some methods of the Base adapter.

Constructor of this class has two parameters.

First is giving us the context. Second is the arraylist with the objects of the ImageModel class.

This arraylist is the data source to populate the grid view.

We will create this arraylist in the MainActivity.java class in the next step.

Now focus on the getView() method.

Compiler will first inflate the grid_item.xml file.

Then it will get the textview and imageview id.

After this, it will set the image and the text in the imageview and textview respectively.

Step 4. Main Activity Code

Now in the MainActivity.java file, add the below source code

I have taken one string array and one integer array.

String array myImageNameList holds the names of the cars.

While integer array myImageList contains the integer reference to the images present in the drawable folder.

Now compiler will populate the arraylist (imageModelArrayList) using the populateList() method.

We will pass these imageModelArrayList to the second parameter of GridBaseAdapter constructor.

Finally, compiler will set the click event for gridview.

When the user clicks on the gridview, it will show a toast.

Output of GridView

When you run the above example, you should get the below output

android gridview

GridView

 

android gridview

Click Event

Second Example With ArrayAdapter

In this example, our adapter will use ArrayAdapter instead of Base adapter.

So make a new fresh android studio project with empty activity.

Step 1. Layout Files Code

In the activity_main.xml file, write down the following lines

Simply one gridview in the main layout.

Now make a new XML layout resource file. Give it a name gv_cell.xml

You should write the below code snippet in the gv_cell.xml file.

This file is the responsible for the view layout of each cell of our gridview.

It has one imageview and one textview.

You can change the text color, text size, text style etc. in this file.

Step 2. Write Main Code

In the MainActivity.java file, add the below code snippet

There are same two variables as we have taken in the first example.

One is string array variable with names of the cars in the string format.

Second is the integer array variable with reference to the images in the drawable folder.

Now focus on the constructor of the GridArrayAdapter. We will create this class in the next step.

Right now let us just see it’s constructor.

First parameter is simply a context. Second one is the reference to the gv_cell.xml file.

Third one is integer array and fourth one is the string array.

Step 3. Making an Array Adapter

Prepare a new JAVA class and name it as GridArrayAdapter.java

Code layout for this file is as the below.

This class is extending the Array Adapter.

getView() method will create the view for each cell.

This method uses gv_cell.xml file to make the layout of the cell.

Then compiler will set the image and text using the integer and string array which are our data source.

See the below image which are outcome of above example.

android gridview

Click Event

android gridview

GridView

Hardik Parsania

I am mobile app developer. I am always passionate about solving complex and real world problems.I have developed many apps with great interest and superior logical skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *