Create a GridView Items XML File

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

In the previous lesson, we added a GridView to a layou that looked like this:

An Android layout with a GridView

The Item 1, Item 2, etc, in the screenshot above will all be replaced by images in our app. The Sub item 1, Sub item 2, etc, will be replaced with a text heading, like "Cat", Dog", etc. To achieve this, we'll create a Custom Adapter, just like we did for the ListView project we created in an earlier project. In place of this, then:

Item and Item Subheading

we'll have this:

A custom Grid Item in Android

Our Custom Adapter will create lots of these items and sub items and then place them in the GridView. Each item comes from a separate XML file. Let's create that now.

To create the XML file, right click on the layout folder in the left of Android Studio:

The layout folder in Android Studio

From the menu that appears, select New > Layout resource file. From the dialogue box that appears, type grid_item as the File name:

The New Resource File dialogue box

Make sure that LinearLayout is the root element, and click OK to create the XML file.

In Design view of grid_items, drag an ImageView from the Images section of the Palette on to either the Component Tree or the blank layout. The Resources dialogue box will appear. Select any drawable you like from here, as it doesn't matter. As the ID for the ImageView, type petImage.

In the Widgets section of the Palette, drag a TextView just below the ImageView (it's easier to do this in the Component Tree). Change the ID of the TextView to petHeading. Now click the link at the bottom of the Properties area that says View all properties. In this section of the properties area, locate the gravity item and change it center. This will centre the heading in the TextView:

The gravity property in Android

Scroll down and click View fewer properties. Now change the layout_height to match_parent:

Setting the layout_height property to match_parent

In the Component Tree, click back onto your petImage ImageView. Again, change the layout_height to match_parent:

Setting a the layout_height property to match_parent:

Your Component Tree should look like this:

An ImageView and TextView in the Android Component Tree

And your layout should look something like this:

An Android layout for grid items

OK, we now have a layout we can use with a Custom Adapter. This grid_item layout will be copied for each pet item we have in our app's grid. In the next lesson, you'll create an array in an Android XML file.