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:
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):
With your GridView selected, type an ID in the properties area on the right. Call your GridView petsGrid:
Your GridView will then look like this:
Now click the View all properties link at the bottom of the properties area:
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:
Now locate the stretchMode property and select columnWidth from the dropdown list:
Finally, locate the verticalSpacing property. Enter a value of 20dp here (this sets the spacing between each row on your grid):
Click the View fewer properties link when you're done. Your layout will look like this:
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.