Simple Gridview Control for Android

Android offers a Gridview control in android.widget.GridView. I built this example project, to illustrate how to create a custom adapter class, a custom item view class, and a custom item data class. This set of classes allows us to conveniently build a complete gridview control, programmatically, without XMLs and add custom data such as a background image for the items, a customized logo image for each item, and a text label.

Similar to the previous article on a custom listview control, here we also need a custom adapter defined in GridViewAdapter.java, that provides the Gridview content by creating several items defined as views in GridViewItemView.java, using the data structure defined in GridViewItemData.java.

By doing so, it gets as simple as calling:

GridView gv = new GridView(this);
RelativeLayout.LayoutParams midParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
midParams.addRule(RelativeLayout.ABOVE,ibMenuBot.getId());
midParams.addRule(RelativeLayout.BELOW,ibMenu.getId());
global_panel.addView(gv,midParams );

int imgs[] = new int[]{ R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,
		R.drawable.pic4,R.drawable.pic5,R.drawable.pic6, R.drawable.pic7,R.drawable.pic8,
		R.drawable.pic9};
String texts[] = new String[]{"FS1000A", "BB Z10", "NaI Crystal","Android", 
		"CDV", "uRADMonitor", "Virtual", "Robot", "Meda"};
//2. setup gridview data
ArrayList itemList = new ArrayList();
for (int i=0;i<50;i++) {
	GridViewItemData item = new GridViewItemData(
			texts[i%9],
			R.drawable.itemback, 
			imgs[i%9],
			i);
	itemList.add(item);
}
//3. create adapter
m_gridviewAdapter = new GridViewAdapter(this, itemList);
//4. add adapter to gridview
gv.setAdapter(m_gridviewAdapter);   
// set number of columns here
gv.setNumColumns(4);
// set default selection
gv.setSelection(2);

You can set the number of columns with setNumColumns. The items have an id, set to the index i , that is useful when catching the click events:

public void onClick(View arg0) {
	int id = arg0.getId();
	// If cancel is pressed, close our app
	if (id == idBack) finish();
	else // click on items
		Toast.makeText(this, "Clicked item:" + id + ":"+
		((GridViewItemData)m_gridviewAdapter.getItem(id)).getLabel(), 
		Toast.LENGTH_SHORT).show();
}

It's so easy! Here's the result:
simple_gridview_control_android

Source Code
The complete code, including the APK, is available here, under GPL license:
HeaderGridViewFooterSimple

This article has 1 Comment

Leave a Reply