In the previous lesson, we added a GridView to a layou that looked like this:
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:
we'll have this:
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:
From the menu that appears, select New > Layout resource file. From the dialogue box that appears, type grid_item as the File name:
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:
Scroll down and click View fewer properties. Now change the layout_height to match_parent:
In the Component Tree, click back onto your petImage ImageView. Again, change the layout_height to match_parent:
Your Component Tree should look like this:
And your layout should look something like this:
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.