ActionScript 3, Flex 4 Script – How to dynamically create CheckBoxes, RadioButtons and add them to the View

Couple of hours I was “googling” to  find the best solution on how to create Checkboxes and Radio Buttons on fly in ActionScript 3  under Flex4. Unfortunately for me, everything, that  I was able to find was either outdated, or just not for me. So I created my script from scratch, and  decided to share it with you, so you could re-use it in your projects ( don’t forget to link on me 🙂 ).

I have made a lot of comments so you could easier understand how it works, but if you have questions, please ask. Also  this function is easy editable so you could adopt it to your needs.

// function receives Array.length and ArrayCollection
private function createButtons(amount:uint, content:ArrayCollection):void{

	var _cb:CheckBox;
	var _rb:RadioButton;
	var _tx: Text;
	var _hb: HBox;

// creating buttons one by one
	for (var i:int = 0; i < amount; i++) {

		_tx = new Text();
		_hb = new HBox();
		_tx.name = "option" +i;
		_tx.width = 200;

// assigning array element to text field
		_tx.text =content.getItemAt(i).toString();
//adding HBox to the view
		options.addChild(_hb);
// if global var _isMultiple is true drawcheckboxes,
// otherwise radioButtons
		if(_isMultiple){
			_cb= new CheckBox();

// giving button a name of array element to process it easier later
			_cb.name=content.getItemAt(i).toString();

// defining gap between the buttons
			_cb.y=i*20;

// adding buttons to the Horizontal Box
			_hb.addChild(_cb);

}else{ // if not _isMultiple

	_rb = new RadioButton();

// giving button a name of array elelment to process it easier later
	_rb.name = content.getItemAt(i).toString();

// assigning radio to the same group
	_rb.groupName = "answers";
	_rb.label ="*";

	_hb.addChild(_rb);

}
// adding text near button
_hb.addChild(_tx);

} // end of loop

} // end of function

options is repesented as:

<mx:Box id="options" >
</mx:Box>

Here is what I’ve got (when _isMultiple is false):

Cheers,

Anatoly

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. Cary Stevenson

    very nice post, i certainly love this website, keep on it

arrow