When populating a ListView
with data, you must specify the format that’s applied to each list item. Each list item in this app displays the String
tag name for one saved search. To specify each list item’s formatting, you’ll create a new layout that contains only a TextView
with the appropriate formatting. Perform the following steps:
1. In the Package Explorer window, expand the project’s res
folder, then right click the layout
folder and select New > Other... to display the New dialog.
2. In the Android node, select Android XML Layout File and click Next > to display the dialog in Fig. 4.16, then configure the file as shown. The new layout’s file name is list_item.xml
and the root element in the layout is a TextView
.
3. Click Finish to create the file.
The IDE opens the new layout in the Graphical Layout editor. Select the TextView
in the Outline window, then set the following properties:
• Id: @+id/textView
—GUI component Ids begin with a lowercase first letter by convention.
• Height (Layout Parameters node): ?android:attr/listPreferredItemHeight
—This value is a predefined Android resource that represents a list item’s preferred height for responding properly to user touches with a minimal chance of touching the wrong item.
• Gravity (Layout Parameters node): center_vertical
—The TextView
should be centered vertically within the ListView
item.
• Text Appearance (TextView node): ?android:attr/textAppearanceMedium
—This is the predefined theme resource that specifies the font size for mediumsized text.
If a list item should display multiple pieces of data, you’ll need a list-item layout that consists of multiple elements, and each element will need an android:id
attribute.
There are many predefined Android resources like the ones used to set the Height and Text Appearance for a list item. You can view the complete list at:
To use a value in your layouts, specify it in the format
?android:attr/resourceName