The following example shows how you can create a Spark TextArea control in Flex 4 which resizes vertically when lines are added or removed by setting the heightInLines property to NaN (Not a Number).

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see http://www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see http://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/2010/01/18/creating-a-vertically-auto-resizing-spark-textarea-control-in-flex-4/ -->
<s:Application name="Spark_TextArea_heightInLines_NaN_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx">
 
    <s:TextArea id="ta"
            heightInLines="{NaN}"
            horizontalCenter="0" verticalCenter="0" />
 
</s:Application>

View source is enabled in the following example.

Or you can set the heightInLines property to NaN using ActionScript, as seen in the following example:

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2010/01/18/creating-a-vertically-auto-resizing-spark-textarea-control-in-flex-4/ -->
<s:Application name="Spark_TextArea_heightInLines_NaN_test"
               xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               initialize="init();">
 
    <fx:Script>
        <![CDATA[
            import spark.components.TextArea;
 
            protected var ta:TextArea;
 
            protected function init():void {
                ta = new TextArea();
                ta.heightInLines = NaN;
                ta.horizontalCenter = 0;
                ta.verticalCenter = 0;
                addElement(ta);
            }
        ]]>
    </fx:Script>
 
</s:Application>

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.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

34 Responses to Creating a vertically auto resizing Spark TextArea control in Flex 4

  1. TK says:

    If I try to set a width for the textarea, it immediately throws a null pointer exception on start. Other than that, really rad!

  2. Mister says:

    I am not finding this example very useful in practice as you can’t set the explicit (or %) width of the TextArea or its left, right, top, bottom constraints. You are left with just the default width of the TextArea. Setting these values throws a null object error which points to line 3357 in the RichEditableText Class:

    // No reflow for explicit lineBreak
    if (hostFormat.lineBreak == “explicit”)
    return false;

    You can set the x, y, maxHeight and minHeight values. Do you know of a way to set its width without throwing an error?

    • Peter deHaan says:

      @Mister,

      Curious. I didn’t see any errors. Which version/build of the Flex 4 SDK are you using? I tried 4.0.0.13479 and it didn’t have any problems (or I just wasn’t looking hard enough).

      Peter

      • Mister says:

        @Peter,

        That might be the issue, I have Flash Builder Beta 2 with SDK 4.0.0. Let me update to the latest SDK and get back to you.

      • Mister says:

        @Peter,

        That did the trick, worked great in the latest SDK. You can’t believe what a big step forward this is in Flex 4 than Flex 3, thanks for the example!

  3. If you’re using the above example with embedded fonts, and you have a maxHeight set, you’ll likely end up with performance problems. More info here: https://bugs.adobe.com/jira/browse/SDK-25899

  4. polyGeek says:

    I couldn’t get it to work with Flex4-Gold bits.

    • Peter deHaan says:

      @polyGeek,

      Works for me:

      <s:TextArea id="ta"
              heightInLines="{NaN}"
              horizontalCenter="0" verticalCenter="0"
              initialize="ta.text = mx_internal::VERSION + '\n' + Capabilities.version;"/>

      Flex 4.0.0.14159, Flash Player WIN 10,0,45,2 (Win 7).

      Peter

  5. code says:

    how can it be implemneted in actionscript:
    e.g:

    private var txtArea:TextArea = new TextArea();
        txtArea.width = 100;
        tctArea.heightInLines = NaN;

    this wont’ work :(

    • Peter deHaan says:

      @code,

      Works for me:

      <?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"
                     initialize="init();">
       
          <fx:Script>
              <![CDATA[
                  import spark.components.TextArea;
       
                  protected var ta:TextArea;
       
                  protected function init():void {
                      ta = new TextArea();
                      ta.heightInLines = NaN;
                      ta.horizontalCenter = 0;
                      ta.verticalCenter = 0;
                      addElement(ta);
                  }
              ]]>
          </fx:Script>
       
      </s:Application>

      I’ll update the example above with the ActionScript-only example and post a SWF.

      Peter

  6. Tyler says:

    Peter you are awesome! I was really dreading having to remake my Flex 3 autosizing textarea component for the spark text area. You just saved me tons of time. Thanks.

  7. Scott Jordan says:

    Has anyone tried this with the Flex 4.1 SDK?

    • Tyler says:

      I just noticed that it no longer works in 4.1. Reverting back to 4.0 and everything was happy. Anyone have any info on this? Was it taken out, changed to something different?

      • Peter deHaan says:

        @Scott Jordan/Tyler,

        I believe you’re seeing http://bugs.adobe.com/jira/browse/SDK-26781.

        Workaround:
        Set the heightInLines property using ActionScript in an updateComplete handler to get the old behavior:

            <s:TextArea id="ta" 
                        horizontalCenter="0" verticalCenter="0"
                        updateComplete="ta.heightInLines = NaN;"/>

        Peter

      • Tyler says:

        Thanks for posting that Peter, guess I shouldve checked to see if someone had already submitted a bug before submitting one myself, however I do not agree with Carol. In the AS 3.0 Reference on the spark TextArea it states this about the heightInLines:

        “If this property is NaN (the default), then the component’s default height will be determined from the text to be displayed.

        This property will be ignored if you specify an explicit height, a percent height, or both top and bottom constraints.

        RichEditableText’s measure() method uses widthInChars and heightInLines to determine the measuredWidth and measuredHeight. These are similar to the cols and rows of an HTML TextArea.

        Since both widthInChars and heightInLines default to NaN, RichTextEditable “autosizes” by default: it starts out very small if it has no text, grows in width as you type, and grows in height when you press Enter to start a new line. ”

        I agree with the developer who submitted the bug that this is a regression, and the documentation is now incorrect. Plus if we have to set the updateComplete listener then its just that much more things going on in the background that didnt need to happen before. I was going to post a comment on that bug, but I guess I cant since it has been closed. So If you can let the powers be now that there are others that dont feel satisfied about this resolution that would be awesome. Anyway if this is a permanent change then updating the docs would be a big help to those who run into it in the future. Thanks for the great blog its been a great help.

      • Tyler says:

        Just one more thing, has anything else been affected by this as well besides the TextArea? Right now we have components that use this (like lists etc) and dont want any surprises if we decide to make the final switch to 4.1.

      • Peter deHaan says:

        @Tyler,

        Correct, I don’t think you can vote on the bug now that it has been resolved as Not a Bug, but you should still be able to add your comments to the bug and state whether you agree or not. I can pass your feedback along to the management team/deciders, but can you also add your comments to the bug report so we can collect them in a single place. That way if we collect enough comments we can reconsider this issue in a future SDK release.

        Thanks,
        Peter

      • Tyler says:

        I tried to do that originally but didn’t see anywhere to add a comment, I just assumed that that option wasn’t available since it had been closed. I’ll Look again.

        Thanks Peter.

  8. Tim John says:

    The workaround is terrible! It totally hogs CPU. I’ve found using the render event rather than updateComplete to be less painful – but it still causes some nasty CPU spikes. Surely it’s not resolved.

    Has a new bug report been filed where we can vote to get it fixed properly?

  9. Tim John says:

    Well, I’ve added my tuppence to the comments on that bug page. If you feel it’s pretty ridiculous for a static TextArea to be hogging CPU, then I think you should too :)

    • Brett Coffin says:

      Yes this is certainly not a decent solution, if you add a max height to your textArea so that when the maxHeight has been reach scrollbars appears, the scroll bars are not working and the updateComplete is firing like crazy… has anyone got a solution ???

  10. Reado says:

    This solution does not work with Flex Hero.

  11. Jeff Spicer says:

    Seeing the several back-and-forths about how to make it work is disconcerting. Isn’t Flex supposed to be rapid development? I’m sticking with Flex 3. It works, even though some things are “slower” or “more expensive”. By the time I learn all the Rube-Goldberg mechanics of Flex 4, technological advances will have made whatever software I’m working on obsolete. But if I stick with Flex 3, the technological advances will have made whatever was “slow” or “expensive” obsolete.

  12. ivy says:

    I can’t believe it! Exactly what i’m looking for!

  13. GeniusIsme says:

    Hello!

    as you know, you cannot use that NaN trick to set spark.TextArea height to content in modern flex enviroment. So take my solution:


    TextArea.addEventListener(TextOperationEvent.CHANGE, function(inEvent:Event):void
    {
    mText.heightInLines = String(TextArea.text).split("\n").length;
    });

  14. Rob says:

    your comment area doesnt like me

  15. Rob says:

    override public function set text(value:String):void{
    super.text = value;
    this.addEventListener(Event.RENDER, autoResizeHandle);
    }
    protected function autoResizeHandle(event:Event):void{
    this.removeEventListener(Event.RENDER,autoResizeHandle);
    super.heightInLines = NaN;
    }

    • Rob says:

      ah, finally

      … I extended the standard TextArea, this worked for me.

      Also add an eventListener for Event.CHANGE with reference to the autoResizeHandler(event) and should you need it an initialize Handler doing the same.

  16. Nuwan says:

    Didn’t work for me with Flash builder 4.5.
    It adds scrolls instead resizing :(

    any solution?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree