Flash / Flex / ActionScript/TextField/focus
Assigning Focus to a Text Field
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.MouseEvent;
public class Main extends Sprite {
public function Main( ) {
var field:TextField = new TextField( );
field.border = true;
field.background = true;
field.type = TextFieldType.INPUT;
addChild(field);
var button:Sprite = new Sprite( );
button.graphics.lineStyle( );
button.graphics.beginFill(0xFFFFFF);
button.graphics.drawRect(0, 0, 100, 50);
button.graphics.endFill( );
button.addEventListener(MouseEvent.CLICK, onClick);
button.y = 100;
addChild(button);
}
private function onClick(event:MouseEvent):void {
stage.focus = TextField(getChildAt(0));
}
}
}
Setting the Insertion Point in a Text Field
package {
import flash.display.Sprite;
import flash.text.TextField;
public class Main extends Sprite {
public function Main( ) {
var field:TextField = new TextField( );
stage.focus = field; // Set the focus to the text field
field.text = "this is example text"; // Set the text value
field.setSelection(0, 0);
trace(field.caretIndex);
addChild(field);
}
}
}
To remove focus from a text field you should assign Stage.focus the null value
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.MouseEvent;
public class Main extends Sprite {
public function Main( ) {
var field:TextField = new TextField( );
field.border = true;
field.background = true;
field.type = TextFieldType.INPUT;
addChild(field);
var button:Sprite = new Sprite( );
button.graphics.lineStyle( );
button.graphics.beginFill(0xFFFFFF);
button.graphics.drawRect(0, 0, 100, 50);
button.graphics.endFill( );
button.addEventListener(MouseEvent.CLICK, onClick);
button.y = 100;
addChild(button);
}
private function onClick(event:MouseEvent):void {
stage.focus = null;
}
}
}