본문 바로가기

Flex/__Flex 3.0

Creating a dynamically resizing TextArea without scrollbars

------------------------------------- DynamicTextArea.as -------------------------------------

package components {
  import flash.events.Event;
  import mx.controls.TextArea;
 
  public class DynamicTextArea extends TextArea{
    public function DynamicTextArea(){
      super();
      super.horizontalScrollPolicy = "off";
      super.verticalScrollPolicy = "off";
      this.addEventListener(Event.CHANGE, adjustHeightHandler);
    }

    private function adjustHeightHandler(event:Event):void{
      trace("textField.getLineMetrics(0).height: " + textField.getLineMetrics(0).height);
      if(height <= textField.textHeight + textField.getLineMetrics(0).height){
        height = textField.textHeight;     
        validateNow();
      }
    }

    override public function set text(val:String):void{
      textField.text = val;
      validateNow();
      height = textField.textHeight;
      validateNow();
    }

    override public function set height(value:Number):void{
      if(textField == null){
        if(height <= value){
          super.height = value;
        }
      }else{       
        var currentHeight:uint = textField.textHeight + textField.getLineMetrics(0).height;
        if (currentHeight<= super.maxHeight){
          if(textField.textHeight != textField.getLineMetrics(0).height){
            super.height = currentHeight;
          }        
        }else{
            super.height = super.maxHeight;         
        }  
      }
    }

    override public function set maxHeight(value:Number):void{
      super.maxHeight = value;
    }
  }
}
 

-------------------------------------------- Test.mxml ----------------------------------

<?xml version="1.0" encoding="utf-8" ?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  xmlns:comp="components.*" creationComplete="init();">
  <mx:Script>
    <![CDATA[
      import mx.controls.Alert;
      import components.*;
     
      private var str:String = "This text will be long enough to trigger " +
        "the TextArea to increase its height.";

      private function setLargeText():void{
        txt1.text = str;
        txt2.text = str;
        txt3.text = str;
        txt4.text = str;
      }
    ]]>
  </mx:Script>
  <comp:DynamicTextArea id="txt1" width="300" height="14"/>
  <comp:DynamicTextArea id="txt2" width="300" height="20"/>
  <comp:DynamicTextArea id="txt3" width="300" height="28"/>
  <comp:DynamicTextArea id="txt4" width="300" height="50"/>
  <mx:Button label="Set Large Text" click="setLargeText();"/>
</mx:Application>

http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&postId=13628&productId=2