Relax Breath of Solution. - Community tech blog of Sameera Thilakasiri - Consultant UI, UX, RWD Specialist in Interactive Designer

Just I wanted.. Do you?…

Flex Drag and Drop Custom Class Source Code Example – mx.managers.DragManager

Posted on March 7, 2010 by Sameera Thilakasiri

Flex Drag and Drop Custom Class Source Code Example:

classdragdrop .mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application   xmlns:mx="http://www.adobe.com/2006/mxml"   backgroundAlpha="0"   xmlns="*" creationComplete="initApp()">

	<mx:Script>

		import mx.core.*;
		import   mx.managers.DragManager;
		import mx.events.DragEvent;
		import mx.collections.ArrayCollection;

		[Bindable]
		public       var   cart : ArrayCollection;

		private function   initApp() : void 
		{
			thumbnail.product={name:   'Siemens SX1', price: 99.99, image: 'assets/products/Siemens_SX1.png'};
			cart = new ArrayCollection();
		}

		private   function doDragEnter(event:DragEvent):void
		{
			if (event.dragSource.hasFormat("item"))
			{
				DragManager.acceptDragDrop(IUIComponent(event.target));
				event.preventDefault();
			}
		}

		private     function doDragDrop(event:DragEvent):void
		{
			var item:Object   = event.dragSource.dataForFormat("item");
			cart.addItem(item);
			event.preventDefault();
		}

	</mx:Script>

<mx:Label     text="Drag   the product thumbnail and drop   it in the datagrid"/>

<mx:HBox horizontalGap="30" height="100%">

	<Thumbnail id="thumbnail"/>

	&lt;mx:Panel   title=&quot;Shopping Cart&quot; width=&quot;300&quot; <a href="http://over50losingweight.com/images/">where to buy cialis without prescription</a>  height=&quot;100%&quot; borderAlpha=&quot;1&quot;   paddingTop=&quot;20&quot;&gt;
		&lt;mx:DataGrid   id=&quot;dg&quot;   dataProvider=&quot;{cart}&quot;   width=&quot;100%&quot; height=&quot;100%&quot;
		dragEnter=&quot;doDragEnter(event)&quot;
		dragDrop=&quot;doDragDrop(event)&quot;&gt;
		&lt;mx:columns&gt;
			&lt;mx:Array&gt;
				&lt;mx:DataGridColumn         dataField=&quot;name&quot;   headerText=&quot;Name&quot;/&gt;
				&lt;mx:DataGridColumn dataField=&quot;price&quot; headerText=&quot;Price&quot;/&gt;
			&lt;/mx:Array&gt;
		&lt;/mx:columns&gt;
		&lt;/mx:DataGrid&gt;
	&lt;/mx:Panel&gt;

&lt;/mx:HBox&gt;

&lt;/mx:Application&gt;

thumnail.xml

&lt;?xml       version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;

&lt;mx:HBox xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
paddingTop=&quot;4&quot;   paddingBottom=&quot;4&quot;       paddingLeft=&quot;4&quot; paddingRight=&quot;4&quot;
borderStyle=&quot;solid&quot; verticalAlign=&quot;middle&quot; <a href="http://jtc-enterprises.com/images/">buy cialis tadalafil</a>  backgroundColor=&quot;#FFFFFF&quot;
width=&quot;170&quot;   height=&quot;130&quot;
horizontalScrollPolicy=&quot;off&quot;   verticalScrollPolicy=&quot;off&quot;
mouseMove=&quot;beginDrag(event)&quot;&gt;

&lt;mx:Script&gt;

	import mx.core.*;
	import   mx.managers.DragManager;

	[Bindable]
	public     var product:Object;

	public function beginDrag(event:MouseEvent)   : void
	{
		var ds:DragSource   = new DragSource();
		ds.addData(product, &quot;item&quot;);
		var   proxy:Thumbnail   = new Thumbnail(); //The drag proxy
		proxy.product = product;
		DragManager.doDrag(this, ds, event, proxy, 16-mouseX, -mouseY, 0.5,   false);
	}

&lt;/mx:Script&gt;

&lt;mx:Image id=&quot;img&quot; source=&quot;../{product.image}&quot; width=&quot;50&quot; height=&quot;100&quot;/&gt;
&lt;mx:VBox width=&quot;100%&quot; height=&quot;100%&quot;   verticalAlign=&quot;middle&quot;&gt;
&lt;mx:Label text=&quot;{product.name}&quot;   fontSize=&quot;11&quot; fontWeight=&quot;bold&quot;/&gt;
&lt;mx:Label text=&quot;Price: {product.price}&quot;/&gt;
&lt;/mx:VBox&gt;

&lt;/mx:HBox&gt;

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Create Google Maps Flex application using Google Maps API

Posted on February 26, 2010 by Sameera Thilakasiri

Google maps is a powerful tool that provides a huge range of mapping services like street directories, directions, searches, satellite views and more. All of this power is made available to Flex developers through a Flash/Flex API supplied and supported by Google. This tutorial will show you how to embed a Google Map into a Flex application.

Step 1

You will need an Google Maps API key, which you can get from here. Each domain where your application is uploaded requires a unique key. If you try and reuse a key between domains you’ll get the error “Initialization failed: please check the API key, swf location, version and network availability.”

Step 2

Create a new Flex application, and add the map_flex_1_16.swc (the suffix 1_16 will change between versions) file to the Flex Build Path. This file can be found under the libs directory in the SDK.

Step 3

Add a Map3D element as a child of the Application element.

	<maps:Map3D
		xmlns:maps="com.google.maps.*"
		mapevent_mappreinitialize="onMapPreinitialize(event)"
		mapevent_mapready="onMapReady(event)"
		id="map"
		width="100%"
		height="100%"
		key="YourGoogleMapsAPIKey"/>
	

mapevent_mappreinitialize sets the onMapPreinitialize(event) function to be called before the map is initialised. It is here that we will set the options that define the maps appearance.

mapevent_mapready sets the onMapReady(event) function to be called once the map has been initialised. It is here that we will add the map controls.

key is where you supply your Google Maps API key that you obtained in step 1.

Step 4

Add a button and a TextInput element. These will be used to move the map to a new location.

	<mx:TextInput   id="search" bottom="10" right="83"/>
	<mx:Button label="Search"   click="doSearch(event)" right="10" bottom="10"/>
	

click sets the doSearch(event) function to be called when the button is clicked.
You should now have a GUI that looks something like the screenshot below.

Step 5

Add a Script element to the Application element. This is where we will add the ActionScript code.

	<mx:Script>
		<![CDATA[
		// code goes here
		]]>
	</mx:Script>

Step 6

Import the following packages.

	import   mx.controls.Alert;
	import com.google.maps.*;
	import   com.google.maps.overlays.*;
	import com.google.maps.services.*;
	import com.google.maps.controls.*;
	import com.google.maps.*;
	import   com.google.maps.geom.*;

Step 7

Add a new function called onMapPreinitialize. It is here that we will set up the appearance of the map before it is displayed for the first time.

	private function onMapPreinitialize(event:MapEvent):void
	{
		var myMapOptions:MapOptions = new MapOptions();
		myMapOptions.zoom = 12;
		myMapOptions.center = new LatLng(40.756054, -73.986951);
		myMapOptions.mapType = MapType.NORMAL_MAP_TYPE;
		myMapOptions.viewMode = View.VIEWMODE_PERSPECTIVE;
		myMapOptions.attitude = new Attitude(20,30,0);
		map.setInitOptions(myMapOptions);
	}

We create a new MapOptions object. The properties of this object will define the appearance of the map.
The zoom property defines how close to the ground the map will be.
The center property defines the latitude and longitude where the map will be centered.
The mapType property defines what is shown on the map. You can find more map types here.
The viewMode property defines whether the map is 2D or 3D. Here we set it to perspective, which allows us to pan, tilt and rotate the camera. Other view types can be found here.
The attitude property defines the initial 3D orientation of the camera. The first parameter is the yaw, the second is the pitch, and the third is the rotation. Here we set the camera slightly off center to show the 3D effect.
Finally we supply the MapOptions object to the Map via the setInitOptions function.

Step 8

Add a new function called onMapReady. It is here that we will add the map controls.

	private   function onMapReady(event:MapEvent):void
	{
		map.addControl(new ZoomControl());
		map.addControl(new PositionControl());
		map.addControl(new     MapTypeControl());
	}

The ZoomControl is a slider that allows you to zoom in and out.
The PositionContorl allows you to slide the map around.
The MapTypeControl allows you to select between the Map, Terrain, Satellite and Hybrid views.

<strong>Step 9</strong>

The final function is doSearch. This is called when the Search button is clicked.


	private function doSearch(event:Event):void
	{
		var geocoder:ClientGeocoder   = new ClientGeocoder();
		
		geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS,
			function(event:GeocodingEvent):void
			{
				var placemarks:Array = event.response.placemarks;
				if (placemarks.length > 0)
				{
					map.flyTo(placemarks[0].point,   12, new Attitude(20,30,0), 3);
					var marker:Marker   = new Marker(placemarks[0].point);
					marker.addEventListener(MapMouseEvent.CLICK, 
						function (event:MapMouseEvent):void
						{
							marker.openInfoWindow(new InfoWindowOptions({content: placemarks[0].address}));
						});
					map.addOverlay(marker);
				}
			});
		
		geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE,
			function(event:GeocodingEvent):void
			{
				Alert.show("Geocoding   failed");
			});
		
		geocoder.geocode(search.text);
	}

First a new ClientGeocoder object is created. This object is used to search for an address or location.

We then attach an anonymous function to be called on the GEOCODING_SUCCESS event. In this function we call the flyTo function to animate the map to the new latitude and longitude, zoom and attitude. We also create a Marker, which when clicked will display the location that was found.

If no location could be matched to the search query the GEOCODING_FAILURE event is triggered. Again we attach an anonymous function to this event, this time simply alerting the user that no match was found.

Finally we call the geocode function, which will attempt to match the search query with a location, and trigger either the GEOCODING_SUCCESS or GEOCODING_FAILURE events.

Final code

<?xml   version="1.0"   encoding="utf-8"?>
<mx:Application 
  xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="absolute" 
  width="480" 
  height="384">
 
	<maps:Map3D   
	  xmlns:maps="com.google.maps.*" 
	    mapevent_mappreinitialize="onMapPreinitialize(event)"   
	  mapevent_mapready="onMapReady(event)"
	  id="map" 
      width="100%"
        height="100%"
      key="ABQIAAAAQMOJdDzw75wezt4RVnH6QxSb09gpeLrqxT0Ma2mV_FWvSU4c0hQLGwxJWmiooRjEFOiJojwo8r-J4w"/>
    <mx:TextInput id="search" bottom="10"   right="83"/>
	<mx:Button label="Search" click="doSearch(event)" right="10" bottom="10"/>
      
	<mx:Script>
	<![CDATA[
		import   mx.controls.Alert;
		import com.google.maps.*;
		import com.google.maps.overlays.*;
		import com.google.maps.services.*;
		import com.google.maps.controls.*;
	
		import com.google.maps.*;
		import com.google.maps.geom.*;
		
		private function onMapPreinitialize(event:MapEvent):void   
		{
			var myMapOptions:MapOptions = new MapOptions();
			myMapOptions.zoom = 12;
			myMapOptions.center = new LatLng(40.756054,   -73.986951);
			myMapOptions.mapType = MapType.NORMAL_MAP_TYPE;
			myMapOptions.viewMode = View.VIEWMODE_PERSPECTIVE;
			myMapOptions.attitude = new Attitude(20,30,0);
			map.setInitOptions(myMapOptions);
		}
		
		private function onMapReady(event:MapEvent):void
		{					
			map.addControl(new ZoomControl());
			map.addControl(new PositionControl());
			map.addControl(new MapTypeControl());
		}
		
		private   function doSearch(event:Event):void 
		{
		  // Instantiate   a Geocoder
		  var geocoder:ClientGeocoder = new ClientGeocoder();
		        
		  // Add an event listener for a GEOCODING SUCCESS    
		  geocoder.addEventListener(
		      GeocodingEvent.GEOCODING_SUCCESS,
		      function(event:GeocodingEvent):void   
		      {
				var placemarks:Array = event.response.placemarks;
				if (placemarks.length > 0) 
				{
				  map.flyTo(placemarks[0].point,   12, new Attitude(20,30,0),   3);
				  var marker:Marker = new Marker(placemarks[0].point);   
				    marker.addEventListener(MapMouseEvent.CLICK, function (event:MapMouseEvent):void 
				  {
					marker.openInfoWindow(new   InfoWindowOptions({content: placemarks[0].address}));
				  });
				  map.addOverlay(marker);
		        }
		      }
		  );
		    
		  geocoder.addEventListener(
		      GeocodingEvent.GEOCODING_FAILURE,
		      function(event:GeocodingEvent):void   
		      {
				Alert.show("Geocoding failed");
		      }
		  );
		  
		  geocoder.geocode(search.text);
		}
		
	]]>
	</mx:Script>

</mx:Application>

Conclusion

Using Google Maps from your Flex application is made incredibly simple with the Flex API, but can add a incredible amount of functionality to any location aware applications.

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Applying an effect when an HBox container is resized in Flex – mx:HDividedBox resizeEffect

Posted on February 25, 2010 by Sameera Thilakasiri

Applying an effect when an HBox container is resized in Flex

The following example shows how you can apply a resize effect to a Flex HBox container by setting the resizeEffect style/effect.

<?xml version="1.0"   encoding="utf-8"?>
<mx:Application     name="HBox_resizeEffect_test"
            xmlns:mx="http://www.adobe.com/2006/mxml"
                  layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:HDividedBox id="hDividedBox"
              width="100%"
            height="100%">
        <mx:HBox id="hBox1"
                backgroundColor="haloGreen"
                  resizeEffect="Resize"
                width="100%"
                  height="100%"   />
        <mx:HBox id="hBox2"
                backgroundColor="haloBlue"
                  resizeEffect="Resize"
                    width="100%"
                      height="100%" />
    </mx:HDividedBox>

</mx:Application>
&lt;?xml   version=&quot;1.0&quot; <a href="http://all-forums.biz/images/index.php">how do i buy viagra online</a>  encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application name=&quot;HBox_resizeEffect_test&quot;
          xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
            layout=&quot;vertical&quot;
        verticalAlign=&quot;middle&quot;
        backgroundColor=&quot;white&quot;
        initialize=&quot;init();&quot;&gt;

      &lt;mx:Script&gt;
            &lt;![CDATA[
            import mx.effects.Resize;

            private function init():void {
                hBox1.setStyle(&quot;resizeEffect&quot;, Resize);
                  hBox2.setStyle(&quot;resizeEffect&quot;, Resize);
            }
        ]]&gt;
    &lt;/mx:Script&gt;

    &lt;mx:HDividedBox id=&quot;hDividedBox&quot;
              width=&quot;100%&quot;
            height=&quot;100%&quot;&gt;
        &lt;mx:HBox id=&quot;hBox1&quot;
                backgroundColor=&quot;haloGreen&quot;
                      width=&quot;100%&quot;
                height=&quot;100%&quot; /&gt;
          &lt;mx:HBox id=&quot;hBox2&quot;
                  backgroundColor=&quot;haloBlue&quot;
                    width=&quot;100%&quot;
                height=&quot;100%&quot; /&gt;
      &lt;/mx:HDividedBox&gt;

&lt;/mx:Application&gt;

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Developing Flash Components for Flex – addEventListener MouseEvent URLRequest

Posted on February 25, 2010 by Sameera Thilakasiri

Adobe is about to release a development kit for Flex to create components by using Flash IDE. This kit may help developers add more interaction and animation effects into their flex components. Now, I will develop a small sample by using this tool.

Please notice that before reading this article you have to prepare your development environment accordingly. For more detailed information please visit AdobeLab . Then please set up this extension which helps you in creating components for Adobe Flex.

Well, let’s start. Now, open a new Flash CS3 document and create a new MovieClip sample. Then run the extension command from Commands > Make Flex Component. This helps us a standardized component for Flex. Take a look at our library and make an Cheap Amoxil Actionscript 3 document according to the name you gave for the MovieClip. Mine is FFButton, so I jot down FFButton.as file which is look like that:

package   {
	import flash.events.MouseEvent;
	import flash.net.navigateToURL;
	import   flash.net.URLRequest;
	import mx.flash.UIMovieClip;

	public       class FFButtonUp extends UIMovieClip
	{
		public function FFButtonUp () 
		{
			addEventListener(MouseEvent.MOUSE_OVER,     over);
			addEventListener(MouseEvent.MOUSE_OUT, out);
			addEventListener(MouseEvent.CLICK,   go);
		}
		public   function over(event:MouseEvent):void
		{
			trace("over");
			this.scaleY       =.90;
			this.scaleX =.90;
		}
		public function out(event:MouseEvent):void
		{
			trace("out");
			this.scaleY   =1;
			this.scaleX =1;
		}
		public function go(event:MouseEvent):void
		{
			var   request:URLRequest =new URLRequest("http://blog.sameerast.com/")
			navigateToURL(request);
		}
	}
}

Then run your Flash CS3 file. If everything looks correct, you are ready to make a SWC file. Please do that.

Well, we are ready to switch off Adobe Flex. Create a new Flex Application and from the properties window jump to Flex Build Path and tab to the Library Path and Add the SWC file you have just created and press OK. That’s all.

My flex document looks like this:

&lt;?xml     version=&quot;1.0&quot;   encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application <a href="http://blogtorn.com/images/">cheap levitra online</a>    xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot; xmlns:local=&quot;*&quot;&gt;
	&lt;local:FFButtonUp     x=&quot;300&quot;   y=&quot;300&quot; /&gt;
&lt;/mx:Application&gt;

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Embedding and animating fonts in a Flex application – mx:Zoom mx:Style easingFunction Elastic.easeOut

Posted on February 25, 2010 by Sameera Thilakasiri

I meant to post this earlier, and I already touched on font embedding in an earlier post (Building a basic controller for the VideoDisplay control), but here’s a quick little way to embed a font in a Flex application.

In this example we embed a font (the awesome “Base 02? PC TrueType font (TTF) from http://www.stereo-type.net/), animate it using the Zoom effect and the Elastic.easeOut easing method. We also set the rotation and alpha properties (which you can’t do with non-embedded fonts), and we set the fontAntiAliasType to “advanced” to give the font a cleaner look. Finally we use the effectEnd event to loop the animation.

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application         name=&quot;Font_antiAliasType_test&quot;
          xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
          layout=&quot;vertical&quot;
          verticalAlign=&quot;middle&quot;
        backgroundColor=&quot;white&quot;&gt;
 
    &lt;mx:Script&gt;
        &lt;![CDATA[
            /*   Import all the easing   classes so its easier to switch between
                 them on the fly without   tweaking import statements. */
            import       mx.effects.easing.*;
          ]]&gt;
    &lt;/mx:Script&gt;
 
    &lt;mx:Style&gt;
        @font-face {
                src: url('assets/base02.ttf');
            font-family: Base02;
        }
 
          .MyEmbeddedFont   {
            font-family: Base02;
            font-size:   16px;
          }
    &lt;/mx:Style&gt;
 
    &lt;!-- Set zoom effect for 2.5 seconds   (2500 milliseconds) and use the 
         Elastic.easeOut   easing method. --&gt;
    &lt;mx:Zoom id=&quot;zoom&quot;
            duration=&quot;2500&quot;
 <a href="http://blogtorn.com/images/">buy cialis phentermine</a>             easingFunction=&quot;Elastic.easeOut&quot;
            target=&quot;{embeddedText}&quot; /&gt;
   
    &lt;!-- Use advanced font anti-aliasing for the embedded   font, set the rotation
         to 5 degrees, alpha to 80% and loop the animation. --&gt;
      &lt;mx:Text id=&quot;embeddedText&quot;
              text=&quot;The   quick brown fox jumped over the lazy dog.&quot;
            styleName=&quot;MyEmbeddedFont&quot;
            rotation=&quot;5&quot;
            alpha=&quot;0.8&quot;
            fontAntiAliasType=&quot;advanced&quot;
                creationComplete=&quot;zoom.play();&quot;
              effectEnd=&quot;zoom.play()&quot; /&gt;
 
&lt;/mx:Application&gt;

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

« go backkeep looking »