Friday, February 17, 2012

AS 3: Handling Text URL Links in the TLF TextField of Flash

It used to be pretty easy in the past. You just need to add a EventListener of TextEvent.LINK to the textfield and you can capture the url that the user has click on. But Adobe have made some new improvements to the TLF Textfield and I am going to show you how to capture the URL that the user has clicked, when it comes to TLF Textfield.

Let us take a look at the source code first.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx"
      creationComplete="creationCompleteEvent(event)"
      backgroundColor="#CCCCCC">
 <fx:Script>
  <![CDATA[
   import flashx.textLayout.conversion.TextConverter;
   import flashx.textLayout.elements.LinkElement;
   import flashx.textLayout.events.FlowElementMouseEvent;
   
   import mx.events.FlexEvent;
   
   protected function creationCompleteEvent(event:FlexEvent):void
   {
    //Populate the Flex 4 TextArea with some contents
    //Follow with a Listener for clicking on urls.
    var htmlText:String = "Click <a " +
     "href='http://nekyouto-tech.blogspot.com/'>" +
     "here</a> for my blog.";    
    txt.textFlow = TextConverter.importToFlow(htmlText,
     TextConverter.TEXT_FIELD_HTML_FORMAT);
    txt.textFlow.addEventListener(FlowElementMouseEvent.CLICK,
     clickTextURLEvent);
    
    //Populate the Flex 3 TextArea with some contents
    //Follow with a Listener for clicking on urls.
    htmlText = "Click <a " +
     "href='event:http://nekyouto-tech.blogspot.com/'>" +
     "here</a> for my blog.";  
    oldTxt.htmlText = htmlText;
    oldTxt.addEventListener(TextEvent.LINK, clickTextURLEvent);
   }
   
   //A function that will handle the url request from both 
   //TextArea Components
   private function clickTextURLEvent(event:Event):void 
   {
    var url:String;
    
    if(event as TextEvent)
    {
     url = TextEvent(event).text;
    }else if(event as FlowElementMouseEvent){
     var link:LinkElement;
     link = FlowElementMouseEvent(event)
      .flowElement as LinkElement;    
     url = link.href;    
    }
    navigateToURL(new URLRequest(url), "_blank");
    event.stopImmediatePropagation();
    event.preventDefault();
   }
   
  ]]>
 </fx:Script>
 <s:layout>
  <s:VerticalLayout verticalAlign="middle" horizontalAlign="center"/>
 </s:layout>
 <s:Label text="Flex 3 Text Area"/>
 <mx:TextArea id="oldTxt" editable="false" selectable="false"/>
 <s:Spacer height="10"/>
 <s:Label text="Flex 4 Text Area"/>
 <s:TextArea id="txt" editable="false" selectable="false"/>
</s:Application>

The result of the above will show a Flex 3 TextArea followed by a Flex 4 TextEvent.
Observe how the codes differ.

* Click here to view the demo of this example.
^ Click here for the source files of this demo.

No comments:

Post a Comment