Adding an Android GridView to a Layout

GridView Project: 1 2 3 4 5 6 7 8 9

Create a new project in Android Studio. Give it the application name Pets. As usual, make sure you select Empty Activity as the template. When your project loads, click on the activity_main.xml tab at the top and delete the default Hello World TextView. In the Palette area, click on Containers, and locate the GridView item:

The Android Studio palette highlighting a GridView

Drag a GridView onto your blank layout.

In the toolbar at the top of Design view, click the Infer Constraints icon (the yellow plus symbol):

The Infer Constraints icon in Android Studio

With your GridView selected, type an ID in the properties area on the right. Call your GridView petsGrid:

Setting an ID for an Android GridView

Your GridView will then look like this:

A layout with a GridView

Now click the View all properties link at the bottom of the properties area:

The View all properties link

We can set three properties here: number of columns, stretch mode, and vertical spacing. Locate the numColumns property first and type a value of 2:

Setting the number of columns for a GridView

Now locate the stretchMode property and select columnWidth from the dropdown list:

Setting the column width for a GridView

Finally, locate the verticalSpacing property. Enter a value of 20dp here (this sets the spacing between each row on your grid):

Setting the vertical spacing for a GridView

Click the View fewer properties link when you're done. Your layout will look like this:

A Two-Column GridView

Now that we have a GridView, we can create an XML file for individual items that make up the grid. We'll do that in the next lesson below.