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="" 
   import flashx.textLayout.conversion.TextConverter;
   import flashx.textLayout.elements.LinkElement;
   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=''>" +
     "here</a> for my blog.";    
    txt.textFlow = TextConverter.importToFlow(htmlText,
    //Populate the Flex 3 TextArea with some contents
    //Follow with a Listener for clicking on urls.
    htmlText = "Click <a " +
     "href='event:'>" +
     "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");
  <s:VerticalLayout verticalAlign="middle" horizontalAlign="center"/>
 <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"/>

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