How to change the background color per row value Suppose you want to color a datagrid depending on the value of a cell. In fact, suppose you have a list of items and their price like that:
| Name | $ |
|---|---|
| Apple | 0.5 |
| Bread | 1.99 |
| Asparagus | 3.0 |
| Banana | 0.8 |
- a cell renderer
- a shape that will be the red background of the cell
package {
import fl.controls.listClasses.CellRenderer;
import fl.controls.listClasses.ICellRenderer;
public class CustomCellRenderer extends CellRenderer
implements ICellRenderer {
public function CustomCellRenderer ():void {
super();
}
public static function getStyleDefinition():Object {
return CellRenderer.getStyleDefinition();
}
override protected function drawBackground():void {
if (_data)
if (_data.price> 1) { setStyle("upSkin", RedColor ); }
super.drawBackground();
}
}
}
You can see (in bold) that I use the column "price" of the row stored in _data to do the condition to show the color. It means that you must have a column called "price" in your data to be able to use this cell renderer.
Let's see now the shape class:
package
{
import flash.display.Sprite;
public class RedColor extends Sprite
{
private var _rectangle:Sprite;
public function RedColor()
{
var _rectangle = new Sprite();
_rectangle.graphics.beginFill(0xff0000,1);
_rectangle.graphics.drawRect(0, 0, 100, 20);
_rectangle.graphics.endFill();
addChild(_rectangle);
}
}
}
The class is very simple but it can't be generic because we can't manage the instances of the class. So, I didn't find a way to set the color in the runtime and I had to create one class per color.
To use those classes, simply add a column to the datagrid like that:
var nameColumn:DataGridColumn = new DataGridColumn("Name");
nameColumn.cellRenderer = CustomCellRenderer ;
_grid.addColumn(nameColumn);
This will add a column in the datagrid which will display the value name with a background red or normal depends on the value of the column price.
Next time, I'll explain how to add a check box, button or movieclip in a cell and add them a custom behavior.