Saturday, April 14, 2012

Customizing the Rows of a BlackBerry TreeField

Here is an example of how we can customize a TreeField of BlackBerry:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class TreeDemo extends MainScreen {
 int parent[] = {1,2,3,4,5,6,7,8,9};
 int child[][] = new int [10][10];
 
 CustomTreeFieldCallback treeCallback = new CustomTreeFieldCallback();
 VerticalFieldManager vm = new VerticalFieldManager(Field.FOCUSABLE | VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
 TreeField myTree = new TreeField(treeCallback, Field.FOCUSABLE);

 public TreeDemo() {
  // TODO Auto-generated constructor stub
  vm.add(new LabelField("Table:"));
  myTree.setRowHeight(27);
  for(int i = parent.length-1; i >= 0 ; i--) {
   parent[i] = myTree.addChildNode(0, "Parent_" + (i+1));
   child[i] = new int[4];
   for(int j = child[i].length-1; j >=0 ; j--) {
    child[i][j] = myTree.addChildNode(parent[i], "Child_"+ (i+1) + "_" + (j+1));
   }
   myTree.setExpanded(parent[i], false);
  }
  vm.add(myTree);
  add(vm);
 }
 
 private class CustomTreeFieldCallback implements TreeFieldCallback {

  public void drawTreeItem(TreeField treeField, Graphics graphics, int node,
    int y, int width, int indent) {
   // TODO Auto-generated method stub
   String string = (String) treeField.getCookie(node);
   int preservedColor = graphics.getColor();
   
   if(treeField.getCurrentNode() == node) {
    graphics.setColor(0x0CCCC0);
   } else {
    graphics.setColor(0x404040);
   }
   graphics.fillRect(0, y, Display.getWidth(), treeField.getRowHeight());
   
   Bitmap iconImage;
   if(treeField.getFirstChild(node) != -1){ // if the node is not a leaf node
    if(treeField.getExpanded(node)) {
     iconImage = Bitmap.getBitmapResource("icon_arrow_down.png");
    } else {
     iconImage = Bitmap.getBitmapResource("icon_arrow_right.png");
    }
    graphics.drawBitmap(0, y, indent, treeField.getRowHeight(), iconImage, 0, 0);
   }

   if( treeField.getCurrentNode() == node ) {
    graphics.setColor(0x404040);   
   } else {
    graphics.setColor(0x0CCCC0);
   }
   graphics.drawText(string, indent, y);
   
   graphics.setColor(preservedColor);
  }

 }
}
I order to associate some actions for clicking on the leaf nodes, the navigationClick or touchEvent methods of TreeField class should be customized.

No comments:

Post a Comment