AS3 Playground: Alternate row colors on dynamic MovieClips

01/02/2010 in RIA View Comments

Below is an example of how to dynamically change the row color of generated movieclips. I find this helpfu when making grid based layouts, buttons, etc. You can have an unlimited amount of row colors by adding to the two if/then statements. Also, you can make this class re-usable by simply adding variables in the public function, passing them into the constructor method from your main fla movieclip instantiation. I try to keep all variables outside the main constructor, or at least in a single area, to help maintain the code and keep it cleaner.

Download the source project here

Alt Row Colors

package com.riareviver{
 
	//Flash Class imports
	import flash.display.MovieClip;
	import flash.text.TextField;
	import flash.events.*;
 
	public class altRowColor extends MovieClip {
 
		//VARIABLE Definitions
		var boxToRepeat:MovieClip;
		var boxText:TextField;
 
		var boxXLoc:int = 50;
		var boxYLoc:int = 50;
		var boxWidth:int = 200;
		var boxHeight:int = 25;
 
		var boxFillColor:uint;
		var boxFillColor01:uint = 0x235880;
		var boxFillColor02:uint = 0x71BDEE;
		var boxFillColor03:uint = 0xCCCCCC;
 
		var altColorDetect:int = 0;
		//How many boxes there are, go ahead...change it and see!
		var boxInstanceCount:uint = 8;
 
		public function altRowColor() {
 
			//Repeat the box, alternating colors as you go.
			for (var i:int = 0; i < boxInstanceCount; i++) {
 
				//Alternate the color based on the detection variable
				if (altColorDetect == 0) {
					boxFillColor = boxFillColor01;
				} else if (altColorDetect == 1) {
					boxFillColor = boxFillColor02;
				} else if (altColorDetect == 2) {
					boxFillColor = boxFillColor03;
				}
				//Create new BOX
				boxToRepeat = new MovieClip();
				boxToRepeat.graphics.beginFill(boxFillColor);
				boxToRepeat.graphics.drawRect(boxXLoc, boxYLoc, boxWidth, boxHeight);
				boxToRepeat.graphics.endFill();
				boxToRepeat.buttonMode = true;
				//A little trick to keep the text from preventing the hand cursor change.
				boxToRepeat.mouseChildren = false;
 
				//Create new TEXTFIELD
				boxText = new TextField();
				boxText.width = 195;
				boxText.height = 15;
				boxText.x = boxXLoc + 10;
				boxText.y = boxYLoc + 5;
				boxText.selectable = false;
				boxText.text = "Box number: " + (i + 1);
 
				//Add all children
				addChild(boxToRepeat);
				//We add the textfield as a child of the box
				boxToRepeat.addChild(boxText);
 
				//Increment the Y Location for the next box
				boxYLoc += boxHeight;
 
				//Alternate the detection variable value
				if (altColorDetect == 0) {
					altColorDetect = 1;
				} else if (altColorDetect == 1) {
					altColorDetect = 2;
				} else if (altColorDetect == 2) {
					altColorDetect = 0;
				}
			}
 
		}
	}
}

Other posts you may find helpful:

,

blog comments powered by Disqus

Switch to our mobile site