Grid Controls

Most widget toolkits offer one or more grid-based controls. Android has a GridView control that can display data in the form of a grid. Note that although we use the term "data" here, the contents of the grid can be text, images, and so on.

The GridView control displays information in a grid. The usage pattern for the GridView is to define the grid in the XML layout (see Listing 4-20), and then bind the data to the grid using an android.widget.ListAdapter.

Listing 4-20. Definition of a GridView in an XML Layout and Associated Java Code

<GridView xmlns:android="" android:id="@+id/dataGrid"

android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10px" android:verticalSpacing="10px"

android:horizontalSpacing="10px" android:numColumns="auto_fit" android:columnWidth="100px" android:stretchMode="columnWidth"

android:gravity="center" />

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


GridView gv = (GridView)this.findViewById(;

Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null);


String[] cols = new String[]{People.NAME}; int[] names = new int[]{};

SimpleCursorAdapter adapter = new SimpleCursorAdapter( this,R.layout.grid_item,c,cols,names);


Listing 4-20 defines a simple GridView in an XML layout. The grid is then loaded into the activity's content view. The generated UI is shown in Figure 4-8.

□ shd« 2:25am 1

Common Controls

(ose Canseco

Joey Copper

Sayed Adleb




Adam Sambo

Figure 4-8. A GridView populated with contact information

The grid shown in Figure 4-8 displays the names of the contacts on the device. We have decided to show a TextView with the contact names, but you could easily generate a grid filled with images and the like.

The interesting thing about the GridView is that the adapter used by the grid is a ListAdapter. Lists are generally one-dimensional whereas grids are two-dimensional. What we can conclude, then, is that the grid actually displays list-oriented data. In fact, if you call getSelection(), you get back an integer representing the index of the selected item. Likewise, to set a selection in the grid, you call setSelection() with the index of the item you want selected.

0 0

Post a comment