AboutFlex.net

flex,air,flash …

Archive for July, 2008

This example shows you how to create a component that extends the TileList and gives you the possibility to sort the element;

This movie requires Flash Player 9

The Application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	creationComplete="{init()}"
	layout="absolute" xmlns:creativesource="it.creativesource.*">
	<mx:Script>
		<![CDATA[
			import it.creativesource.SortObject;
			import it.creativesource.DisplayItem;
			import mx.collections.ArrayCollection;

			[Bindable]
			private var dp:ArrayCollection=new ArrayCollection();

			[Bindable]
			private var fields:ArrayCollection=new ArrayCollection();

			private function init():void{

				var field1:SortObject=new SortObject("field1");
				var field2:SortObject=new SortObject("field2");
				var field3:SortObject=new SortObject("field3");

				field1.label="Sort by field1";
				field2.label="Sort by field2";
				field3.label="Sort by field3";				

				field1.isNumeric=true;
				field2.isNumeric=true;
				field3.isNumeric=true;				

				fields.addItem(field1);
				fields.addItem(field2);
				fields.addItem(field3);

				for(var i:int=0;i<10;i++){
					var obj:Object={};
					obj['field1']=i;
					obj['field2']=Math.round(Math.random()*100);
					obj['field3']=Math.round(Math.random()*100);

					dp.addItem(obj);

				}

			}

		]]>
	</mx:Script>
	<creativesource:SortableTileList 

		itemRenderer="it.creativesource.DisplayItem"
		dataProvider="{dp}"
		x="10" y="10"
		width="400" height="480"
		sortableFields="{fields}"
	 />
	<mx:Button x="418" y="10" label="Button"/>
	<mx:Button x="418" y="468" label="Button"/>

</mx:Application>

The SortableTileList.as:

package it.creativesource
{
	import flash.events.MouseEvent;

	import mx.collections.ArrayCollection;
	import mx.collections.ICollectionView;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.controls.TileList;
	import mx.events.CollectionEvent;

	public class SortableTileList extends TileList
	{
		[Bindable]
		private var _header:ArrayCollection=new ArrayCollection();
		[Bindable]
		private var _fields:ICollectionView=new ArrayCollection();
		private var _currentSort:Sort=new Sort();

		public function SortableTileList(){
			super();
			_fields.enableAutoUpdate();

		}

		override protected function createChildren():void{
			super.createChildren();
			this.y+=22;
			this.height-=22;
		}

		public function set sortableFields(fields:ArrayCollection):void{

			_header=new ArrayCollection();
			_fields=fields
			if(!_fields.hasEventListener(CollectionEvent.COLLECTION_CHANGE))
				_fields.addEventListener(CollectionEvent.COLLECTION_CHANGE,createBtn);

		}

		private function createBtn(e:CollectionEvent=null):void{
			for(var i:int=0;i<_header.length;i++){
				try{
					removeChild(_header.getItemAt(i) as SortBtn);
				}catch(e:*){}

			}

			_header=new ArrayCollection()

			for(i=0;i<_fields.length;i++){
				if(!(_fields[i] is SortObject)){

					throw new Error("Fields must be SortObject");

				}

				var b:SortBtn=new SortBtn();
				b.label=_fields[i].label;
				b.field=_fields[i].field;
				b.styleName="SortBtn";
				b.isNumeric=_fields[i].isNumeric;
				addChild(b);
				_header.addItem(b)
			}

		}

		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{ 

			super.updateDisplayList(unscaledWidth,unscaledHeight);

			for(var i:int=0;i<_header.length;i++){

				var b:Object=_header.getItemAt(i);
				b.x=this.width/_header.length*i
				b.y=-22;
				b.width=this.width/_header.length;
				b.height=22;
				b.buttonMode=true;
				b.addEventListener(MouseEvent.CLICK,handleDownSortBtn)

			}

		}

		private function handleDownSortBtn(e:MouseEvent=null):void{
			try{
				if(_currentSort.fields[0].name==e.target.field){
					var desc:Boolean=!_currentSort.fields[0].descending

				}
			}catch(e:*){
				desc=false;
			}

			_currentSort = new Sort();
     		_currentSort.fields = [new SortField(e.target.field,true,desc,e.target.isNumeric)];
     		sortIt(_currentSort)

     	  	for(var i:int=0;i<_header.length;i++){
     			var b:Object=_header.getItemAt(i);
     			if(b!=e.target){
     				b.restoreDefault();
     			}
     		}

		}

		public function set sortStyleName(value:Object):void{
			for(var i:int=0;i<_header.length;i++){
     			var b:Object=_header.getItemAt(i);
     			b.styleName=value;
     		}

		}

		private function sortIt(sort:Sort):void{

			dataProvider.sort = sort;

     		dataProvider.refresh();

		}

	}
}

The SortObject.as:

package it.creativesource
{

	public class SortObject
	{
		public function SortObject(field:String){
			this.field=field
		}
		public var label:String="";
		public var field:String="";
		public var isNumeric:Boolean=false;
	}
}

The SortBtn.as:

package it.creativesource
{
	import flash.events.MouseEvent;

	import mx.controls.Button;
	import mx.controls.Image;

	public class SortBtn extends Button
	{
		public function SortBtn()
		{
			super();
			arrow.source=arrowImage;

		}
		[Embed(source="assets/arrow.swf" , symbol="arrow" )]

        [Bindable]
        public var arrowImage:Class;
		private var arrow:Image=new Image();
		private var _isDown:Boolean=false;

		override protected function createChildren():void{

			super.createChildren();
			addChild(arrow);
			arrow.alpha=.5;
			arrow.visible=false;

		}

		override protected function mouseDownHandler(event:MouseEvent):void{
			super.mouseDownHandler(event);
			_isDown=true

		}
		public function restoreDefault():void{

			arrow.rotation=0
			arrow.visible=false
		}

		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
			super.updateDisplayList(unscaledWidth,unscaledHeight)
			if(_isDown){
				arrow.visible=true;
				swapChildren(arrow,this.getChildAt(this.numChildren-2));
				arrow.alpha=.2
				_isDown=false;
				arrow.rotation+=180

			}else{
				swapChildren(arrow,this.getChildAt(this.numChildren-3));
				arrow.alpha=.5
			}
			arrow.width=10;
			arrow.height=7;
			arrow.x=this.width-13;
			arrow.y=10;
		}
		public var field:String="";
		public var isNumeric:Boolean=false;
	}
}

The DisplayItem.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"  borderStyle="solid" height="124" width="99">

	<mx:Label x="10" y="11" text="Field1"/>
	<mx:Text x="55" y="11" text="{data.field1}" width="35" height="18"/>

	<mx:Label x="10" y="37" text="Field2"/>
	<mx:Text x="56" y="37" text="{data.field2}" width="35" height="18"/>

	<mx:Label x="10" y="63" text="Field3"/>
	<mx:Text x="56" y="63" text="{data.field3}" width="35" height="18"/>

</mx:Canvas>

This example shows you how to display Google suggestes inside the AutoComplete component
developed by the Adobe Flex Team ;

The example uses a class developed for Air content by the AboutFlex Team
and a bridge in PHP developed by msdevstudio.com
that allows us to use the class in an online content;

This movie requires Flash Player 9

the Application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	creationComplete="init()"
	layout="vertical"
	xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:ns1="it.creativesource.*" width="500" height="500">
	<mx:Script>
	<![CDATA[
		import it.creativesource.GoogleSuggester;

		private var gs:GoogleSuggester ;

		private function init():void{

			gs=new GoogleSuggester ();
			gs.addEventListener(gs.SUGGESTED,displayResults)
		}

		private function findSuggests(e:KeyboardEvent):void{

			if(e.keyCode!=38)
			if(e.keyCode!=40){
				gs.findSuggests(e.currentTarget.typedText)
			}
		}
		private function displayResults(e:Event):void{
			try{
				autoComplete.dataProvider=e.currentTarget.dataProvider;
				if(e.currentTarget.dataProvider.length>1)
					autoComplete.open();
			}catch(e:*){}

		}
	]]>
</mx:Script>

	<ns1:AutoComplete id="autoComplete" 

		keepLocalHistory="true"
		keyUp="findSuggests(event)"
		lookAhead="true"  labelField="word"  />

</mx:Application>

The GoogleSuggester.as class:

package it.creativesource
{
    import flash.display.Sprite;
    import flash.events.Event;

    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;

    [Event(name="suggested", type="flash.events.Event")]

    public class GoogleSuggester extends Sprite
    {
        public const SUGGESTED:String='suggested';
        private var _dataProvider:ArrayCollection=new ArrayCollection();

        public function GoogleSuggester()
        {
        }

        public function findSuggests(string:String):void{
            var hs:HTTPService=new HTTPService();
            /*use our server-side script send.php to get suggestions*/           

            hs.url=Path.URL+"send.php?q="+string+"&cp="+string.length;

            hs.addEventListener(ResultEvent.RESULT,parseResults)

            hs.send();
            _dataProvider=new ArrayCollection();
            var item:Object={};
            item['word'] = string;
            _dataProvider.addItem(item);

        }

        protected function parseResults(e:ResultEvent):void{
           try{
	            var tmp:Array=e.result.split('new Array')[1].split(', "');

	            for (var i:int=1;i<tmp.length-1;i+=2){

	                tmp[i]=tmp[i].replace('"',"");
	                tmp[i]=tmp[i].replace('\\x27',"'");
	                var item:Object={};
	                item['word'] = tmp[i];
	                _dataProvider.addItem(item);

	            }
           }catch(e:*){}
            dispatchEvent(new Event('suggested'));
        }

        public function get dataProvider():ArrayCollection{
            return _dataProvider;
        }

    }
}

the Path.as class:

package it.creativesource
{
	public class Path
	{

		static public const URL:String="http://www.aboutflex.net/labs/googleSuggesterOnLine/";

	}
}

The send.php script ( thanks to msdevstudio ):

<?php
  $host="http://www.google.com";
  $text=$_GET['q'];
  $len=$_GET['cp'];

  $text=str_replace(" ","%20",$text);

  $instruction="/complete/search?hl=en&client=suggest&js=true&q=".$text."&cp=".$len;
  $url=$host.$instruction;

 if ((double)phpversion() >= 4.2)
    {
        ini_set('allow_url_fopen', '1');
    } 

  $s = @file_get_contents($url);
    if (empty($s))
    {
        echo "";
    }
    else
    {
	echo $s;
     }
?>

The AutoComplete.as class here

Local SharedObject

Posted by Fedele Marotti under ActionScript 3, Flash, Flex

This example shows you how to use local SharedObject in ActionScript 3;

This movie requires Flash Player 9

The Application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	creationComplete="init()"
	 xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
	<![CDATA[
		import mx.controls.Alert;

		private var so:SharedObject;
		private function init():void{
			so=SharedObject.getLocal(application.name);
			textArea.text=so.data.text;
		}
		private function saveSO():void{
			so.data.text=textArea.text;
		}

		private function loadSO():void{
			Alert.show(so.data.text);
		}

		private function clearSO():void{
			so.clear();
		}
	]]>
</mx:Script>
	<mx:Button click="{ saveSO()}" x="10" y="135" label="Save"/>
	<mx:Button click="{ loadSO()}" x="83" y="135" label="Load"/>
	<mx:Button click="{ clearSO()}" x="156" y="135" label="Clear"/>
	<mx:TextArea id="textArea" x="10" y="10" width="201" height="117"/>
</mx:Application>

Google Translator Widget

Posted by Fedele Marotti under AIR, ActionScript 3, Flex

This is an application developed using Flex and Air, that uses the power of Google Translate to translate.

If you have suggestions or comments you can write here.

Cheers,
AboutFlex Team

This example shows you how to create a component to display money;

This movie requires Flash Player 9

The application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute" xmlns:creativesource="it.creativesource.*" viewSourceURL="http://www.aboutflex.net/labs/moneyFormatter/srcview/index.html">
	<creativesource:MoneyField floatRound="2"  moneySymbol="$" y="50" x="50" />
</mx:Application>

The component:

package it.creativesource
{
	import flash.events.KeyboardEvent;

	import mx.controls.TextInput;

	public class MoneyField extends TextInput
	{
		private var _intSeparator:String='.';
		private var _floatSeparator:String=',';
		private var _floatRound:int=2;

		private var _moneySymbol:String='€';

		public function MoneyField()
		{
			super();
			addEventListener(KeyboardEvent.KEY_UP,handleKeyUp)
			super.restrict='0-9'+_floatSeparator;
		}

		//restrict
		override public function set restrict(value:String):void{

		}
		public function set moneySymbol(value:String):void{
			_moneySymbol=value
		}
		public function set floatRound(value:int):void{
			_floatRound=value
			if(_floatRound<1)
			super.restrict='0-9'
		}
		public function set intSeparator(value:String):void{
			if(value.length>1)
			throw new Error("The int separator is invalid");
			_intSeparator=value;
		}

		public function set floatSeparator(value:String):void{
			if(value.length>1)
			throw new Error("The float separator is invalid");
			_floatSeparator=value;
			restrict='0-9'+_floatSeparator;
		}

		public function get intSeparator():String{
			return _intSeparator;
		}
		public function get floatSeparator():String{
			return _floatSeparator;
		}

		private function handleKeyUp(e:KeyboardEvent=null):void{
			super.text=text.split(_moneySymbol)[0];
			if(e.charCode>47 && e.charCode<58){
				formatText();
			}else{
				if(String.fromCharCode(e.charCode)==_floatSeparator)
				for(var j:int=0;j<_floatRound;j++)
					super.text=super.text+"0";
				formatText();
			}
		}
		private function formatText():void{
			super.text=text.split(_moneySymbol)[0];
			if(text.length==0)
				return

			var intPart:String=text.split(_floatSeparator)[0];
			var floatPart:String=text.split(_floatSeparator)[1];
			var tmp:String=''
			var newText:String=''

			for(var i:int=intPart.length;i>=0;i--){
				if(intPart.charAt(i)!=_intSeparator && intPart.charAt(i)!=_moneySymbol)
				tmp+=intPart.charAt(i);
			}

			for(i=0;i<tmp.length;i++){

				if(i%3==0 && i!=0 && i!=tmp.length)
				newText+=_intSeparator
				newText+=tmp.charAt(i);

			}
			tmp=''
			for(i=newText.length;i>=0;i--){

				tmp+=newText.charAt(i);
			}

			super.text=tmp;

			var isFloat:Boolean=false;
			try{
				isFloat=floatPart.length>0
			}catch(e:*){}

			if(isFloat){
				if(floatPart.length>_floatRound){
					super.text=super.text+_floatSeparator+floatPart.substring(0,_floatRound)

				}else{

					super.text=super.text+_floatSeparator+floatPart
					for(i=floatPart.length;i<_floatRound;i++)
					super.text=super.text+"0";
				}
			}else{
				selectionBeginIndex=text.length;
				selectionEndIndex=text.length;

			}
			super.text=super.text+_moneySymbol;

		}
		override public function set text(value:String):void{
			super.text=value;
			formatText()

		}
	}
}