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:

  1.  
  2. GridView gv = new GridView(this);
  3. RelativeLayout.LayoutParams midParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
  4. midParams.addRule(RelativeLayout.ABOVE,ibMenuBot.getId());
  5. midParams.addRule(RelativeLayout.BELOW,ibMenu.getId());
  6. global_panel.addView(gv,midParams );
  7.  
  8. int imgs[] = new int[]{ R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,
  9. R.drawable.pic4,R.drawable.pic5,R.drawable.pic6, R.drawable.pic7,R.drawable.pic8,
  10. R.drawable.pic9};
  11. String texts[] = new String[]{"FS1000A", "BB Z10", "NaI Crystal","Android",
  12. "CDV", "uRADMonitor", "Virtual", "Robot", "Meda"};
  13. //2. setup gridview data
  14. ArrayList<GridViewItemData> itemList = new ArrayList<GridViewItemData>();
  15. for (int i=0;i<50;i++) {
  16. GridViewItemData item = new GridViewItemData(
  17. texts[i%9],
  18. R.drawable.itemback,
  19. imgs[i%9],
  20. i);
  21. itemList.add(item);
  22. }
  23. //3. create adapter
  24. m_gridviewAdapter = new GridViewAdapter(this, itemList);
  25. //4. add adapter to gridview
  26. gv.setAdapter(m_gridviewAdapter);
  27. // set number of columns here
  28. gv.setNumColumns(4);
  29. // set default selection
  30. gv.setSelection(2);
  31.  

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:

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

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

Related Post

This article has 1 Comment

Leave a Reply