Flex AutoResizable Textarea

I’ve been quite busy those past weeks, working on some great projects and cool devices (Stay tune one will be available in all high tech shops soon).

Recently, I faced a very simple Flex problem. I had to work with a Textarea but I needed it to be autoresizable, and ALSO I had be able to set so constraints such as : maxchars displayed and maxheight. I had a quick look on the internet but I didn’t find a conponent fitting my needs. You may find some example using mx_internal properties but I try to avoid using this namespace…for many reasons.

Anyway, I crafted my own Autoresizable Textarea and share it to everyone who want to play with/improve/crash/burn/..etc it.


///////////////////////////////
// Author: Guillaume Nachury
//
//         Advanced Textarea
//
// -> Auoresize feature with
//             -> MaxChar limiter
//            -> MaxHeight limiter
///////////////////////////////

package
{
 import mx.controls.TextArea;

 public class AdvancedTextarea extends TextArea
 {

 private var _autoResize:Boolean =  false;
 private var _lineOffset:int = 5;
 public var fullText:String="";

 public function AdvancedTextarea(isAutoResize:Boolean=false)
 {
 super();
 _autoResize = isAutoResize;
 }

 //overrides        
 override public function set maxChars(i:int):void{
 super.maxChars = i;
 doValidations();
 }

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

 override public function set text(s:String):void{
 //limit the number of chars if there's a limit
 fullText = s;
 if(super.maxChars>0 && s.length > super.maxChars){
 s = s.substring(0, super.maxChars)+"...";    
 super.text = s;
 }
 super.text = s;

 validateNow();
 doValidations();
 }

 private function doValidations():void{
 if(super.text != null && super.text.length >0){

 //limit the height if there's a limit
 if(!isNaN(super.maxHeight)){
 var textH:int = this.textField.measuredHeight+_lineOffset;
 if(textH > super.maxHeight && _autoResize == true){
 this.height = super.maxHeight;
 }
 else{
 if(_autoResize == true)    this.height = this.textField.measuredHeight+_lineOffset;

 }

 }
 else{
 if(_autoResize == true){
 this.height = this.textField.measuredHeight+_lineOffset;
 }

 }
 }
 }

 public function set autoResize(b:Boolean):void{
 _autoResize = b;
 doValidations();
 }

 }
}

Advertisements