Creating a simple text editor using the Spark TextArea control in Flex 4

The following example shows how you can create a simple rich text editor control in Flex 4 using the Spark TextArea control and using the getFormatOfRange() and setFormatOfRange() methods.

Full code after the jump.

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.

For more information on getting started with Flex 4 and Flash Builder 4, see the official Adobe Flex Team blog.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/24/creating-a-simple-text-editor-using-the-spark-textarea-control-in-flex-4/ -->
<s:Application name="Spark_TextArea_setFormatOfRange_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo">
 
    <fx:Script>
        <![CDATA[
            import flash.text.engine.FontPosture;
            import flash.text.engine.FontWeight;
            import flashx.textLayout.formats.TextAlign;
            import flashx.textLayout.formats.TextDecoration;
            import flashx.textLayout.formats.TextLayoutFormat;
            import mx.events.ColorPickerEvent;
            import mx.events.FlexEvent;
            import spark.events.IndexChangeEvent;
 
            protected function editor_selectionChangeHandler(evt:FlexEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                fontDDL.selectedItem = txtLayFmt.fontFamily;
                sizeDDL.selectedItem = txtLayFmt.fontSize;
                boldBtn.selected = (txtLayFmt.fontWeight == FontWeight.BOLD);
                italBtn.selected = (txtLayFmt.fontStyle == FontPosture.ITALIC);
                underBtn.selected = (txtLayFmt.textDecoration == TextDecoration.UNDERLINE);
                colorCP.selectedColor = txtLayFmt.color;
                lineBtn.selected = txtLayFmt.lineThrough;
 
                switch (txtLayFmt.textAlign) {
                    case TextAlign.LEFT:
                        txtAlignBB.selectedIndex = 0;
                        break;
                    case TextAlign.CENTER:
                        txtAlignBB.selectedIndex = 1;
                        break;
                    case TextAlign.RIGHT:
                        txtAlignBB.selectedIndex = 2;
                        break;
                    case TextAlign.JUSTIFY:
                        txtAlignBB.selectedIndex = 3;
                        break;
                    default:
                        txtAlignBB.selectedIndex = -1;
                        break;
                }
            }
 
            protected function fontDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.fontFamily = fontDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function sizeDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.fontSize = sizeDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function boldBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.fontWeight = (txtLayFmt.fontWeight == FontWeight.BOLD) ? FontWeight.NORMAL : FontWeight.BOLD;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function italBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.fontStyle = (txtLayFmt.fontStyle == FontPosture.ITALIC) ? FontPosture.NORMAL : FontPosture.ITALIC;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function underBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.textDecoration = (txtLayFmt.textDecoration == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function colorCP_changeHandler(evt:ColorPickerEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.color = colorCP.selectedColor;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function txtAlignBB_changeHandler(evt:IndexChangeEvent):void {
                if (txtAlignBB.selectedItem) {
                    var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                    txtLayFmt.textAlign = txtAlignBB.selectedItem.value;
                    editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                    editor.setFocus();
                }
            }
 
            protected function lineBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                txtLayFmt.lineThrough = lineBtn.selected;
                editor.setFormatOfRange(txtLayFmt,
                                editor.selectionAnchorPosition,
                                editor.selectionActivePosition);
                editor.setFocus();
            }
        ]]>
    </fx:Script>
 
    <s:Panel title="SimpleTextEditor"
            width="400"
            horizontalCenter="0" verticalCenter="0">
        <s:layout>
            <s:VerticalLayout gap="0" />
        </s:layout>
        <s:TextArea id="editor"
                focusEnabled="false"
                width="100%" height="100%"
                minHeight="200"
                selectionChange="editor_selectionChangeHandler(event);">
            <s:textFlow>
                <s:TextFlow paragraphSpaceBefore="20">
                    <s:p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et nibh lorem. Nulla ut velit magna. Nunc quis libero ac orci porta tincidunt eget in lorem. Aenean vitae nisi vitae urna lacinia congue. Duis nec leo turpis. Phasellus dui orci, lacinia in dictum lacinia, ullamcorper a tortor. Suspendisse lacinia, turpis vel euismod gravida, turpis dui vulputate libero, vel consequat enim sem nec mauris. Curabitur vitae magna vel neque accumsan commodo vitae quis ipsum. Nullam ac condimentum elit. Integer eget magna ac mi fermentum luctus. Ut pharetra auctor pulvinar. Duis lobortis, nulla at vestibulum tincidunt, ante neque scelerisque risus, ac dignissim nunc nisl rhoncus risus. Cras pretium egestas purus, a commodo nunc vehicula at. Fusce vestibulum enim in mi hendrerit a viverra justo tempor. Maecenas eget ipsum ac mauris dictum congue eu id justo.</s:p>
                    <s:p>Aliquam tincidunt tempor nisi id porta. Aenean risus dolor, tincidunt a ultrices in, laoreet eu ante. Mauris vel lacus neque, ut scelerisque eros. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec vel lacus sit amet erat vehicula malesuada id in augue. Sed purus massa, placerat non imperdiet nec, venenatis a nulla. Donec vel ligula leo, in rhoncus arcu. Duis semper bibendum facilisis. Duis nibh lorem, egestas rutrum tincidunt non, vulputate accumsan nulla. Nunc ligula nisl, ultrices ut tempor quis, rutrum et enim. Nullam accumsan scelerisque ante id pretium. Mauris nibh metus, blandit in varius congue, pharetra sit amet sem. Phasellus tincidunt lacus quis est semper ut rhoncus sem pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pulvinar, enim eu consectetur venenatis, dui tortor commodo ante, sit amet sagittis libero odio cursus neque. Aliquam a dui non eros placerat euismod. In at mattis felis. Suspendisse potenti. Morbi posuere condimentum lacus. Suspendisse tellus magna, viverra ac mattis vel, adipiscing eget lectus.</s:p>
                    <s:p>Etiam ut eros lectus. Praesent nec massa nibh. Cras venenatis, ligula in condimentum euismod, nisl lorem hendrerit lacus, a imperdiet odio est et odio. Suspendisse eu orci ut augue commodo gravida sed eu risus. Vestibulum venenatis erat ac metus ullamcorper blandit. Integer et sem enim. Vivamus a arcu metus. Nunc sollicitudin commodo placerat. Maecenas vehicula, massa et auctor tempor, felis leo commodo lorem, eget pulvinar felis turpis nec erat. Mauris imperdiet gravida felis a eleifend.</s:p>
                    <s:p>Suspendisse mattis tempor fringilla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed molestie arcu. Praesent ut tellus sed orci blandit tristique non eget est. Sed interdum feugiat nisi, sit amet aliquet enim sodales non. Maecenas in velit sit amet tellus tincidunt dapibus. Vivamus est eros, iaculis et venenatis a, malesuada vel lacus. Aliquam vel orci tortor. Etiam ornare ante eget massa dignissim a auctor nunc pellentesque. Pellentesque sodales porta nisi, pretium accumsan eros tincidunt vitae. Cras facilisis accumsan purus ultricies lacinia. Praesent consequat elit imperdiet tellus vehicula ut ornare mauris mattis. Suspendisse non tortor nisl. Etiam ac pretium est.</s:p>
                    <s:p>Maecenas tristique, velit aliquam faucibus ornare, justo erat porta elit, sed venenatis neque mi ac elit. Nullam enim metus, gravida ac euismod sit amet, commodo vitae elit. Quisque eget molestie ante. Nulla fermentum pretium augue non tristique. Praesent in orci eu diam ultrices sodales ac quis leo. Aliquam lobortis elit quis mi rutrum feugiat. Aenean sed elit turpis. Duis enim ligula, posuere sit amet semper a, pretium vel leo. Etiam mollis dolor nec elit suscipit imperdiet. Sed a est eros.</s:p>
                </s:TextFlow>
            </s:textFlow>
        </s:TextArea>
        <mx:ControlBar width="100%" cornerRadius="0">
            <mx:ToolBar width="100%" horizontalGap="5">
                <s:DropDownList id="fontDDL"
                        width="150"
                        change="fontDDL_changeHandler(event);">
                    <s:dataProvider>
                        <s:ArrayList source="[Arial,Verdana,Times New Roman,Trebuchet MS]" />
                    </s:dataProvider>
                </s:DropDownList>
                <s:DropDownList id="sizeDDL"
                        width="60"
                        change="sizeDDL_changeHandler(event);">
                    <s:dataProvider>
                        <s:ArrayList source="[8,10,12,14,16,24,36,72]" />
                    </s:dataProvider>
                </s:DropDownList>
                <s:ToggleButton id="boldBtn"
                        label="B"
                        fontWeight="bold"
                        width="30"
                        click="boldBtn_clickHandler(event);" />
                <s:ToggleButton id="italBtn"
                        label="I"
                        fontStyle="italic"
                        width="30"
                        click="italBtn_clickHandler(event);" />
                <s:ToggleButton id="underBtn"
                        label="U" 
                        textDecoration="underline"
                        width="30"
                        click="underBtn_clickHandler(event);" />
                <s:ToggleButton id="lineBtn"
                        label="S"
                        lineThrough="true"
                        width="30"
                        click="lineBtn_clickHandler(event);" />
                <mx:ColorPicker id="colorCP"
                        change="colorCP_changeHandler(event);" />
                <s:ButtonBar id="txtAlignBB"
                        arrowKeysWrapFocus="true"
                        labelField="label"
                        width="120"
                        change="txtAlignBB_changeHandler(event);">
                    <s:dataProvider>
                        <s:ArrayList>
                            <fx:Object label="L" value="{TextAlign.LEFT}" />
                            <fx:Object label="C" value="{TextAlign.CENTER}" />
                            <fx:Object label="R" value="{TextAlign.RIGHT}" />
                            <fx:Object label="J" value="{TextAlign.JUSTIFY}" />
                        </s:ArrayList>
                    </s:dataProvider>
                </s:ButtonBar>
            </mx:ToolBar>
        </mx:ControlBar>
    </s:Panel>
 
</s:Application>

View source is enabled in the following example.

This entry is based on a beta version of the Flex 4 SDK and therefore is very likely to change as development of the Flex SDK continues. The API can (and will) change causing examples to possibly not compile in newer versions of the Flex 4 SDK.

49 thoughts on “Creating a simple text editor using the Spark TextArea control in Flex 4

  1. Hi!
    I was trying to run the code, but when I put it on FB, it said it could not find the class IndexChangeEvent, then, I downloaded the SDK build 8786 and now it tells me that my class SimpleMotionPath is defined more than once and I can not run the example, what can I do?

    Thanks!

  2. Daniel Cisneros,

    I just compiled the above example in 4.0.0.8811 and it worked fine for me.
    What if you try running the above example in a brand new Flex project without the SimpleMotionPath code?

    Peter

  3. Hi,

    I’m using build 235740 and I get the following error when I try to compile.

    “1046: Type was not found or was not a compile-time constant: IndexChangeEvent”

    Is this an issue with the build I’m currently using or possible something else?

    Sipho

  4. Hi Peter,

    I was using the default SDK with Flash Builder 4 (Beta) build 235740. But I just downloaded SDK 4.0.0.7219 from labs.adobe.com and had the same issue the app not compiling, same error. Do you have a link for a newer SDK version I can download?

    Thanks,
    Sipho

    1. Sipho,

      Flex SDK 4.0.0.7219 is the same SDK that shipped with Flash Builder 4 beta 1.
      You can grab the latest builds from http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4 Grab one of the Nightly Builds (most recent version is 8811 from Sat Jul 25, 2009).

      Then, just follow the instructions at “Downloading and installing Flex 4 SDK builds from opensource.adobe.com (Flash Builder 4 beta Edition)” to get the build working in your Flash Builder 4 beta.

      Peter

  5. Hi,
    i want to apply bullets on spark textarea control but not getting any help with TextLayoutFormat class
    can any help me out how to add this functionality.
    Thanks in advance for any help.

  6. Ok, its finally working for me, I’ve downloaded SDK 4.0.0.8811 and also had to add ‘netmon.swc’ to my build path so that it could compile properly.

    Thanks for the responses Peter :)

  7. BIDI doesn’t work. i’m trying to put hebrew and english together…..
    is this bug wasn’t solve???

  8. This example wont work in Beta 1, cause it has TextArea.getSelectionFormat() function instead of
    TextArea.getFormatOfRange()
    (dunno, if they do the same..)

  9. Hi peter,

    Simple Rich Text editor is working fine.But when i am selecting the formatting values( font size, font weight ,color etc) first and later inserting the text then these formatting values are not being applied on the text(formatting values are resetting to default).

    Is there any way to get this functionality.

  10. Can you assign a “styleName” or “id” to the TextLayoutFormat object, so it can be reused? If so, we could create a list of TextLayoutFormat “styles” and apply them to parts of text, that would be nice.

    Thanks,
    Lance

    1. @Lance,

      Something like this, perhaps?:

      <?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:formats="flashx.textLayout.formats.*"
              initialize="init();">
       
          <fx:Script>
              <![CDATA[
                  import flash.text.engine.FontWeight;
                  import flashx.textLayout.formats.TextLayoutFormat;
       
                  private const tf1:TextLayoutFormat = new TextLayoutFormat();
                  private const tf2:TextLayoutFormat = new TextLayoutFormat();
       
                  private function init():void {
                      tf1.fontWeight = FontWeight.BOLD;
                      tf1.fontSize = 32;
       
                      tf2.fontWeight = FontWeight.NORMAL;
                      tf2.fontFamily = "Times New Roman";
                      tf2.color = 0xFF0000; // red
                  }
              ]]>
          </fx:Script>
       
          <fx:Declarations>
              <formats:TextLayoutFormat id="tf3" fontWeight="bold" fontSize="14" color="0xFF00FF" />
          </fx:Declarations>
       
          <s:HGroup left="10" top="10">
              <s:Button id="btn1"
                      label="Apply text layout format #1"
                      click="ta.setFormatOfRange(tf1, ta.selectionAnchorPosition, ta.selectionActivePosition);" />
              <s:Button id="btn2"
                      label="Apply text layout format #2"
                      click="ta.setFormatOfRange(tf2, ta.selectionAnchorPosition, ta.selectionActivePosition);" />
              <s:Button id="btn3"
                      label="Apply text layout format #3"
                      click="ta.setFormatOfRange(tf3, ta.selectionAnchorPosition, ta.selectionActivePosition);" />
          </s:HGroup>
       
          <s:TextArea id="ta" selectionHighlighting="always" horizontalCenter="0" verticalCenter="0">
              <s:textFlow>
                  <s:TextFlow>
                      <s:p>1) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>2) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>3) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>4) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>5) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>6) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>7) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>8) The quick brown fox jumps over the lazy dog.</s:p>
                      <s:p>9) The quick brown fox jumps over the lazy dog.</s:p>
                  </s:TextFlow>
              </s:textFlow>
          </s:TextArea>
       
      </s:Application>

      Peter

  11. Also, what is your recommended way of styling text? Would you have to go through and use a text editor, or have you found a simple solution where you can just say “styleName” or “id” = “myStyle”, and it would apply styles from either a TextLayoutFormat object, or from some CSS parsed into a TextLayoutFormat object. Right now I am manually parsing CSS into TLF objects, caching them in a Dictionary, looping through Elements with “getChildByID”, and for-loop-assigning the TLF properties to the element. Seems like there could be something easier.

    Thanks a lot,
    Lance

    1. @Lance,
      I was playing around with this a bit more, and this seems to work, but I’m finding that text selection gets a bit “quirky”, which may mean I’m not using it correctly:

      <?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">
       
          <s:HGroup  horizontalCenter="0" verticalCenter="0">
              <s:TextArea id="ta" selectionHighlighting="always">
                  <s:textFlow>
                      <s:TextFlow>
                          <s:userStyles>
                              <s:format id="tf1" color="0xFF0000" fontWeight="bold" />
                              <s:format id="tf2" color="0xFF00FF" fontStyle="italic" />
                          </s:userStyles>
                          <s:p>1) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p format="{tf1}">2) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p>3) The quick <s:span format="{tf2}">brown fox</s:span> jumps over the lazy dog.</s:p>
                          <s:p format="{tf1}">4) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p>5) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p>6) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p>7) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p format="{tf1}">8) The quick brown fox jumps over the lazy dog.</s:p>
                          <s:p>9) The quick brown fox jumps over the lazy dog.</s:p>
                      </s:TextFlow>
                  </s:textFlow>
              </s:TextArea>
          </s:HGroup>
       
      </s:Application>

      The best place to ask would probably be the Text Layout Framework forums at http://forums.adobe.com/community/opensource/tlf/.

      Let me know what you find out. Sounds like it may make a good set of blog posts.

      Peter

    2. Here’s another one…

      <?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">
       
          <fx:Script>
              <![CDATA[
                  import spark.utils.TextFlowUtil;
       
                  XML.ignoreWhitespace = false;
              ]]>
          </fx:Script>
       
          <fx:Declarations>
              <fx:String id="flow" source="flow1.xml" />
          </fx:Declarations>
       
          <s:TextArea id="ta" textFlow="{TextFlowUtil.importFromString(flow)}" />
       
      </s:Application>

      And the text flow object, flow1.xml, is as follows:

      <?xml version="1.0" encoding="utf-8"?> 
      <TextFlow xmlns="http://ns.adobe.com/textLayout/2008"> 
          <format id="redBold" color="0xFF0000" fontWeight="bold" />
          <format id="greenItal" color="#00FF00" fontStyle="italic" />
          <p format="greenItal">The quick brown <span format="redBold">fox jumps over</span> the lazy dog.</p>
      </TextFlow>

      Peter

  12. HELP PLEASE

    I need implement it with link operation:
    I have in TextArea with :

     <a href="http://www.example.com" rel="nofollow">link example</a>  TextFlow

    I need to change an textInput.text when the curson is on href tag ‘link example’ words.

    private function editor_selectionChangeHandler(evt:FlexEvent):void
                 {
                     ///
                            myTxt.text = evt ???????
                  }

    how can I read href tag ?
    thanks

  13. Hello Peter;
    I noticed that underline works to add an underline, and when selected the underline button shows that it’s underlined, but the problem is that you cannot undo the underline.

    Thanks for the blog,
    John

    1. @jdesko,

      Right you are. I never noticed that in my example above.
      Try the following code:

      <?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">
          <s:controlBarContent>
              <s:ToggleButton id="underlineBtn"
                      label="U"
                      textDecoration="underline"
                      width="40"
                      change="underlineBtn_change(event);" />
          </s:controlBarContent>
       
          <fx:Script>
              <![CDATA[
                  import flashx.textLayout.formats.TextDecoration;
                  import flashx.textLayout.formats.TextLayoutFormat;
       
                  protected function underlineBtn_change(evt:Event):void {
                      var styles:Vector.<String> = new <String>['textDecoration'];
                      var startPos:uint = txtArea.selectionAnchorPosition;
                      var endPos:uint = txtArea.selectionActivePosition;
                      var fmt:TextLayoutFormat = txtArea.getFormatOfRange(styles, startPos, endPos);
                      fmt.textDecoration = (ToggleButton(evt.currentTarget).selected) ? TextDecoration.UNDERLINE : TextDecoration.NONE;
                      txtArea.setFormatOfRange(fmt, startPos, endPos);
                      txtArea.setFocus();
                  }
              ]]>
          </fx:Script>
       
          <s:TextArea id="txtArea"
                  text="The quick brown fox jumps over the lazy dog."
                  selectionHighlighting="always"
                  horizontalCenter="0" verticalCenter="0" />
       
      </s:Application>

      Peter

  14. the same is possbile with the flex builder 3 RICH TEXT EDITOR and TLF

    i am using Flex 3.2 sdks FL-10 and TLF

    i want the same in flex 3

  15. Hi,
    the Underline function is not working properly, you can add a Line under the Text but cant get rid of it anymore. Any idea how to fix ?

  16. Here is the Underline Fix:

    in the underBtn_clickHandler(evt:MouseEvent) function change the following:

    txtLayFmt.textDecoration = (txtLayFmt.fontStyle == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;

    to:

    txtLayFmt.textDecoration = (txtLayFmt.textDecoration == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;
  17. Love the editor, except I’m having some issues formating a selected portion of text with my own embedded fonts. Using the fonts I have embedded, I’m able to set my entire textArea to any font I wish, however when I want to change the font for only the selected text, it changes the selected text to a default Times New Roman. If I use the same code with the standard fonts (Arial, Verdana, etc.) it works perfectly fine. Has anyone else seen this problem, or know what I’m doing wrong?

    I’m loading my fonts via an swf that I compiled through FB4 (the same as my project). Here’s an example of one of them:

    @font-face {
        font-family: NimbusSansNovusTBlack;
        src: url("fonts/NimbusSansNovusT_Black.otf");
        embedAsCFF: true;
    }

    Here is the code the changes the font, pretty much the same thing as what’s in the source code for this site’s example:

    var txtLayFmt:TextLayoutFormat = focusedTextArea.getFormatOfRange(null,
    					focusedTextArea.selectionAnchorPosition,
    					focusedTextArea.selectionActivePosition);
     
    				txtLayFmt.fontFamily = fontDrop.selectedItem;
    				focusedTextArea.setFormatOfRange(txtLayFmt,
    					focusedTextArea.selectionAnchorPosition,
    					focusedTextArea.selectionActivePosition);
    				focusedTextArea.setFocus();

    And finally, here’s my font ComboBox:

    <mx:ComboBox includeIn="State1" id="fontDrop" x="304" y="10" editable="true" change="setFont();">
        <mx:dataProvider>
            <s:ArrayList source="[Arial,Verdana,Times New Roman,Trebuchet MS,NimbusSansNovusTMedium,NimbusSansNovusTBlack,NimbusSansNovusTLightRo1,NimbusSansNovusTRegular,HelveticaLTStd-Cond,OptimaLTStd]" />
        </mx:dataProvider>
    </mx:ComboBox>

    Any help would be greatly appreciated. Thanks!

    -Christian

    1. @Christian,

      What if you try embedding the Arial, Times New Roman, fonts too so everything is using embedded. I don’t know that I’ve tried the Spark TextArea too much with a mix of device and embedded fonts (but I vaguely recall that the mx:RichTextEditor control possibly wasn’t too happy when you tried that).

      Peter

    2. Also, I’d make sure you’re using the latest Flex 4 SDK nightly build. I think there may have been some TLF improvements around this within the last couple months (post Flex 4 Beta 2 SDK).

      Peter

      1. @Peter

        Thanks for the help. I tried the newest SDK nightly build, but that didn’t work. I also gave the RichTextEditor a try just for fun, and no dice as well. I’m currently working on embedding the device fonts, and I think that certainly has something to do with it. I can now use my embedded fonts (and the now-embedded device fonts) to change the selected text’s font. The only catch is that all of my buttons, comboBoxes, etc. that were using the default device fonts are now not showing any text (presumably because there’s something wrong with the font). I’m gonna look into this more, but barring I can fix that problem, it looks like all fonts do need to be embedded for my issue to be fixed.

  18. Hi,
    I am not able to type the text in Hindi language. When i try to type the text in Hindi it will appear in a ‘?'(question mark).
    I was trying this by using the RichTextEditor but today i try with Text Layout Framework. but still not able to write.
    Above, as you mentioned running application, i tried to write there also but not able to do.
    Can you please give me some solution is it possible with flex or not.
    I am trying to getting the solution for this from the last 1 month.
    Please if anyone have a solution or have any idea that flex doesnt support please feel free to write a mail to me.

    Thanks
    Monika

    1. @Monika,

      Is the RichTextEditor or Text Layout Framework example using a font with Hindi characters? I think the default font is Verdana which may or may not include the desired characters in that font face.

      Peter

  19. Hi peter,

    I tried with RichTextArea with or without Text Layout Framework.
    The above example give the source code as well as the running applicationin in this bolg only, i tried to write the text in hindi there only but not able to wirte.
    And t he default font is Arial.
    Please refer the upper most example and the text area”Simple Text Editor” and try to write the hindi, it will appear in ‘?’.
    Accept Hindi, i am able to write in every language.

    Please help me out.
    Thanks.
    -Monika

  20. hey frnds,
    i have created simple tlf editor, and want to allow user to select text and give link to that text./
    but dont know how to do this?
    is any idea there ?
    thx in advanced,
    :)

  21. I have tried this demo ,but I need to modify the namespace fo mx.The original code is “……xmlns:mx=”library://ns.adobe.com/flex/halo”>” and I have revised it to “……xmlns:mx=”library://ns.adobe.com/flex/mx”>”,and then it works .

    but I still have a little confuse aboute “halo” and “mx”.

    thank you,a good guy!

    O(∩_∩)O哈哈~

    1. “halo” was the old namespace in beta builds of Flex 4.0, but it was updated to “mx” in the final release.

      There are a number of older examples on this site that I haven’t had the time to update yet.

      Peter

  22. Hi Peter,
    thank you very much for all your helpful examples!!

    I need to extend your editor for greek letters. Problem is the linebreak after pasteTextScrap() .

    var entAlpha:String = “Α”;

    protected function setAlpha(event:Event):void{
    var txtFlowEditor:TextFlow;
    var editManager:EditManager = editor.textFlow.interactionManager as EditManager;
    txtFlowEditor = TextConverter.importToFlow(entAlpha, TextConverter.TEXT_FIELD_HTML_FORMAT);
    editManager.pasteTextScrap(new TextScrap(txtFlowEditor));
    }

    Can you help?

    Ellen

  23. Hi,

    for chemical formulars in my application I need to convert the tag.
    I get the formula from the DataBase. I am able to display the formula but not to edit, because every part stays single.
    I would need to merge them to a group but I don’t know how. I tried some different ways but nothing works.

    // variable with content from DataBase
    var txtFormulaXMLFOTemp:String = “”;

    while(txtFormulaXMLFOTemp.length > 0){

    formulaXMLFOSubStart = txtFormulaXMLFOTemp.search(“” );
    formulaXMLFOSubEnd = txtFormulaXMLFOTemp.search(“”);

    if(formulaXMLFOSubStart > -1 && formulaXMLFOSubEnd > -1 && (formulaXMLFOSubEnd > formulaXMLFOSubStart)){

    txtFormulaXMLFO = txtFormulaXMLFOTemp.substring(0, formulaXMLFOSubStart);
    txtFormulaXMLFOStart = txtFormulaXMLFO;
    txtFormulaXMLFOSub = txtFormulaXMLFOTemp.substring((formulaXMLFOSubStart + 5), formulaXMLFOSubEnd);
    txtFormulaXMLFOTemp = txtFormulaXMLFOTemp.substring((formulaXMLFOSubEnd + 6), txtFormulaXMLFOTemp.length);

    var richTxtFormulaFOStart:RichEditableText;
    richTxtFormulaFOStart = new RichEditableText();
    richTxtFormulaFOStart.text = txtFormulaXMLFOStart;
    hGroupEditView.addElement(richTxtFormulaFOStart);

    var richTxtFormulaFOSub:RichEditableText;
    richTxtFormulaFOSub = new RichEditableText();
    richTxtFormulaFOSub.text = txtFormulaXMLFOSub;
    richTxtFormulaFOSub.textFlow.baselineShift = “subscript”;
    richTxtFormulaFOSub.textFlow.dominantBaseline = “ascent”;
    richTxtFormulaFOSub.validateNow();
    hGroupEditView.addElement(richTxtFormulaFOSub);
    }
    else{
    txtFormulaXMLFO = txtFormulaXMLFOTemp;
    txtFormulaXMLFOEnd = txtFormulaXMLFO;
    var richTxtFormulaFOEnd:RichEditableText;
    richTxtFormulaFOEnd = new RichEditableText();
    richTxtFormulaFOEnd.text = txtFormulaXMLFOEnd;
    hGroupEditView.addElement(richTxtFormulaFOEnd);
    }

    My future goal:
    Below “editorFO” is a ButtonBarButton with some further possibilities to change the formula (bold, underline, add greek letters).
    Any help is most appreciated.
    Thanks, Ellen

  24. Hi Peter,
    This is terrific. I am trying to set up some interactive tutorials on using different software. I would like to use and probably modify this for this purpose. Looking at the licence it is free to use but requires attribution. How would you like it attributed? ie in the code?
    Thanks in advance

  25. First.. TY for your time in posting and maintaining great examples likes.
    I have a question if u could point me in the right direction please:
    I using your code on a “<s:TextArea"

    Using PHP, mysqli (service) I'm trying to store the data with formatting to a MySql "Text" field.

    If I enter and format the text as follows:
    —-
    line one
    next line font 16
    next line bold
    next line italics
    next line underline
    next line font sans
    end line
    —-
    the carriage returns are preserved but all the formatting is gone in the Database.

  26. Never mind found my answer on your
    “http://blog.flexexamples.com/2009/07/25/exporting-a-textflow-object-in-flex-4/” post
    thank you again for these examples.

  27. Hi, I am having trouble saving the data. when i tried to save data it doesn’t save it as formatted.

    Any help Please.
    Thanks

  28. Hi Peter.

    I’m trying to run this code as a mobile project so I removed all the MX stuff but I’m getting a null object reference at these lines:

    txtLayFmt.fontStyle = (txtLayFmt.fontStyle == FontPosture.ITALIC) ? FontPosture.NORMAL : FontPosture.ITALIC;

  29. Hey –

    just wanted to quickly post and say THANK YOU for all the invaluable examples you’ve posted. This one in particular just saved me a lot of time trying to figure out selections/text-formats.

    Much appreciated!

Comments are closed.