Flex Snippet Tutorial - Using The TextRange Class

Skill

Flex Snippet Tutorial - Using The TextRange Class

Posted in:

The guys over at Adobe have provided us with a lot of classes that simply make our job as developers very easy. Today I am going to go over one of these classes, TextRange. This class allows us to bind to one of several components and get/set properties about the text in that selection. The properties that can be modified include the text itself and the styles for the text. The namespace for this class is mx.controls.textClasses and the Adobe documentation page can be found here for further info.

Below is the example application we are going to build today. It is a relatively simple program but it shows off the power of the TextRange class. You can type into the textArea and then highlight sections and change the properties of that selection using the buttons at the bottom. The color picker will also change the text color of the selected text. In this example I use a TextArea but you can use TextRange with Label, Text, TextInput, or RichTextEditor.

Get Adobe Flash player

As usual the first task we are going to do is setup the user interface. It is a very simple interface with nothing out of the ordinary. It has a panel, textarea, colorpicker, label, and several buttons which we use to control the text selection changes. So our starting interface code looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="331"
   height="389" viewSourceURL="/files/Tutorials/Flex/TextRange/TextRangeTutorial.mxml">
  <mx:Panel x="0" y="0" width="331" height="389"
     layout="absolute" title="Simple TextRange Usage">
    <mx:TextArea id="txtSlate" x="10" y="10" width="282" height="269"/>
    <mx:Button x="10" y="287" label="Increase Font Size" width="135"/>
    <mx:Button x="10" y="317" label="Decrease Font Size"/>
    <mx:ColorPicker x="270" y="287"/>
    <mx:Label x="156" y="289" text="Choose Font Color:"/>
    <mx:Button x="241" y="317" label="Bold"/>
    <mx:Button x="177" y="317" label="Italic"/>
  </mx:Panel>
</mx:Application>

Next we are going to setup our TextRange. We do this using a function that we call when the TextArea dispatches the creationComplete event. I called this function "initTextArea" which will reside in a <mx:Script> tag. Also in our script tag we create a new var, which will hold our TextRange object we are going to use for the selection. When creating the new TextRange object we pass the UIComponent we are going to bind to as the first argument, and the second argument is whether we are going to let the TextRange object modify the selection. There are two more arguments that can be passed in that restrict what text in the UIComponent the TextRange object can bind to - but since we didn't we are bound to whatever the user selects. We also update our <mx:TextArea> to have the event call in it.

The first code here goes directly after the opening application tag.

<mx:Script>
 <![CDATA[
   import mx.controls.textClasses.TextRange;
   import mx.events.ColorPickerEvent;
   
   private var textSelection:TextRange;
   
   private function initTextArea():void
   {
     textSelection = new TextRange(txtSlate, true);
   }
 ]]>
</mx:Script>

The second piece is our new TextArea tag.

<mx:TextArea id="txtSlate" x="10" y="10" width="282" height="269"
   creationComplete="initTextArea()"/>

The remaining code is pretty straightforward, so we are going to run through it real quick. We add a couple more functions to our script tag which handle click events for the buttons and change events for the colorpicker. In these functions we can update the appropriate properties of the TextRange and instantly we should see the changes to our selected text. Putting it all together we get the following code for our application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="331"
   height="389" viewSourceURL="/files/Tutorials/Flex/TextRange/TextRangeTutorial.mxml">
  <mx:Script>
   <![CDATA[
     import mx.controls.textClasses.TextRange;
     import mx.events.ColorPickerEvent;
   
     private var textSelection:TextRange;
   
     private function initTextArea():void
     {
       textSelection = new TextRange(txtSlate, true);
     }
   
     private function increaseFontSize():void
     {
       textSelection.fontSize++;
     }
   
     private function decreaseFontSize():void
     {
       textSelection.fontSize--;
     }
   
     private function changeFontColor(eventObj:ColorPickerEvent):void
     {
       textSelection.color = eventObj.color;
     }
   
     private function changeFontBold():void
     {
       if(textSelection.fontWeight == "bold")
       {
         textSelection.fontWeight = "normal";
       }
       else
       {
         textSelection.fontWeight = "bold";
       }
     }
   
     private function changeFontItalic():void
     {
       if(textSelection.fontStyle == "italic")
       {
         textSelection.fontStyle = "normal";
       }
       else
       {
         textSelection.fontStyle = "italic";
       }
     }
   ]]>
 </mx:Script>
  <mx:Panel x="0" y="0" width="331" height="389"
     layout="absolute" title="Simple TextRange Usage">
    <mx:TextArea id="txtSlate" x="10" y="10" width="282" height="269"
       creationComplete="initTextArea()"/>
    <mx:Button x="10" y="287" label="Increase Font Size"
       width="135" click="increaseFontSize()"/>
    <mx:Button x="10" y="317" label="Decrease Font Size"
       click="decreaseFontSize()"/>
    <mx:ColorPicker x="270" y="287" change="changeFontColor(event)"/>
    <mx:Label x="156" y="289" text="Choose Font Color:"/>
    <mx:Button x="241" y="317" label="Bold" click="changeFontBold()"/>
    <mx:Button x="177" y="317" label="Italic" click="changeFontItalic()"/>
  </mx:Panel>
</mx:Application>

Well I hope that this small tutorial gives some good information on how to use the TextRange class and modifying selected text from user components. As always, leave any comments or questions below.

Don
12/20/2007 - 23:03

Like the text formatter, it's great, too bad I'm just getting started with Flex, the popupwin one does not work for me, problem may lie in correctly referencing the component...

Thanks.

reply

Manish
12/27/2007 - 03:34

good effords ..it helps me alot

reply

Alex Barton
03/09/2008 - 08:55

This is very useful but how could I change it so that the text is updated without having to select it?

Thanks

reply

Kalmár Nagy András
03/18/2008 - 11:47

Hi, this is a very useful intro to using the textRange class, I would really be interested in adding images to a piece of text. Could you give me some pointers on you would go about doing it?

reply

Tess
03/31/2008 - 08:50

Hi, I'm working with your textrange code but I'm trying to not hardcode the target for the changes. Instead of:

textSelection = new TextRange(txtSlate, true);

Is there a way to change txtSlate into a variable that has the current focus, so I can use these buttons on multiple text areas?

thank you so much for your help!
Tessy

reply

Tess
03/31/2008 - 09:58

Got it! Here's how you can focus on any text area without knowing its id!

********mxml********

***************

Enjoy!

reply

Tess
03/31/2008 - 10:02

ok dang, it filters out mxml code. so i'll have to crudely type it out:

private function initTextArea(event:Event):void
{
  textSelection = new TextRange(
      (event.currentTarget)as UIComponent, true);
}
   
private function addToolListener(event:Event):void
{
  (event.currentTarget).addEventListener(
      MouseEvent.CLICK, initTextArea);
}

Then on the textareas, add the following:

creationComplete= "addToolListener(event)"

Hope this helps!

reply

Amar Shukla
06/09/2008 - 04:07

reallly a gud article for a beginner..thnx alot

reply

Sunny
03/28/2009 - 02:01

Can u modify to apply kerning to a particular chunk with that chunk having different font-face.
I simply want to ask to use various font embeddings in different sections of same textarea.
Though in my custom as3 components. I had provided the user this facility using css.
But this time I want to use TextRange.
I possible pls reply soon.
Thnx

reply

art
07/16/2009 - 12:35

YES .. please upload the CUSTOM Font example!
would be interesting to see if its possible.
is it? thanks!

reply

vfmarrese
12/05/2009 - 07:30

Hallo,
con you explain me a simple example to add TextRange to this code without use MXML:

        import mx.controls.*;
        import mx.controls.textClasses.TextRange;

        public function init ():void{

                var testooutput:String ="testo";

                var testo:Text;
                testo = new Text();
                addChild(testo);
                testo.text = testooutput;

                }

Thanks in advice!

reply

Anup
01/05/2010 - 00:27

How do I use it? It dose't works:(

reply

dollu
05/15/2010 - 14:31

can TextRange be used in a datagrid too, any suggestions to use there

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors