Search code examples
actionscript-3flashairtlf

How to set focus on TLFTextField


like the title said. How to set focus on TLFTextField on runtime?

I already do some research and find a few question answered in SO like this How to set focus to a TLFTextfield object

And on few forum, they said to use this code

stage.focus = txt;

or

txt.stage.focus = txt;

or

txt.textFlow.interactionManager.setFocus();

But none works for me.. I'd try on simple project and still failed..

I need to show a MovieClip with a TLFTextField and focus on it.. So user can just type to edit the TLFTextfield.

my code:

public function TFLayer() {
    tf = new TLFTextField();
    tf.width = 400;
    tf.height = 30;
    tf.x = 300;
    tf.y = 300;
    tf.border = true;
    tf.type = TextFieldType.INPUT;
    tf.backgroundColor = 0xffffff;
    tf.text = "Lorem ipsum";
    addChild(tf);

    tf.textFlow.interactionManager.setFocus();
}

Solution

  • Given an editable TLFTextField named tf, you can enable focus with:

    import flashx.textLayout.edit.EditManager;
    
    tf.textFlow.interactionManager = new EditManager();
    tf.textFlow.interactionManager.selectRange(0, 0);
    tf.textFlow.interactionManager.setFocus();
    

    Using this method, the text field is focused ready to receive input from the keyboard; however, the cursor will not blink. Therefore, there's no visual indication of focus.

    TLFTextFields are not optimal for user input. Consider using TextField or TextArea instead.