Home and Learn: Android Course


Adding an Android GridView to a Layout

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 of earlier versions of Android Studio, click on Containers, and locate the GridView item:

The Android Studio palette highlighting a GridView

In later versions, the GridView control has been moved under the Legacy item, for some strange reason (it's not deprecated):

The Legacy > GridView control in the Android Studio 3 Palette

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 or the wand in later versions of Android Studio):

The Infer Constraints icon in Android Studio

Infer Constraints icon in Android Studio 3

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: (Later version of Android Studio won't show the Item and Sub Item. You'll just have a whiote screen.)

Setting an ID for a GridView in Android Studio 3

Now click the View all properties link at the bottom of the properties area in earlier Android Studio Version, or exapnd the All Attributes item in later versions.

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

Your layout will look like this (later versions of Android Studio will still see the blank white screen):

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.

Back to the Android Contents Page

 


Email us: enquiry at homeandlearn.co.uk