SentineL
SentineL

Reputation: 4732

Set textfield editable in runtime

I have a textfield, which should be editable after pressing button:

playerName = new TextField();
playerName.autoSize = "left";
playerName.styleSheet = styleSheet;
playerName.type = TextFieldType.DYNAMIC;
playerName.tabEnabled = false;
playerName.maxChars = 14;
playerName.background = false;
playerName.backgroundColor = 0x1e904b;
...
var boldStyleObject:Object = {};
boldStyleObject.fontSize = 12;
boldStyleObject.fontFamily = "Verdana";
boldStyleObject.color = "#ffffff";
boldStyleObject.fontWeight = "bold";
styleSheet.setStyle(".bold", boldStyleObject);
boldStyleName = "bold";
...
playerName.htmlText = "<span class='" + boldStyleName + "'>" + player.name + "</span>";
...
private function ChangeName (event:Event):void
{
    playerName.type = TextFieldType.INPUT;
    playerName.background = true;
    playerName.addEventListener(KeyboardEvent.KEY_DOWN, DoneEditing);
    stage.focus = playerName;
}
...

private function DoneEditing (event:KeyboardEvent):void
{
    var target:TextField = event.target as TextField;

    if (event.keyCode == 27)
    {
        target.text = editBackup;
        DisactivateTextField(target);
    }
    else if (event.keyCode == 13 && target == playerName && playerName.text.length > 3)
    {
        DisactivateTextField(target);
    }
}

private function DisactivateTextField(field:TextField):void
{
    field.type = TextFieldType.DYNAMIC;
    field.background = false;
    field.removeEventListener(KeyboardEvent.KEY_DOWN, DoneEditing);
}

All working fine, except TextField's editability. Why?

Upvotes: 0

Views: 157

Answers (2)

SentineL
SentineL

Reputation: 4732

The problem was in html style. In some reason, TextField with htmlText, styled via styleSheet, can't be edited. You should use TextField.defaultTextFormat property to style text you whant to edit.

Upvotes: 0

inhan
inhan

Reputation: 7470

Pressing a button requires a MouseEventso make sure you're adding the right event listener to yourbutton. Also, make sure you're checking the user input to terminate editing or evaluating the input itself.

private function something():void {
    yourBtn.addEventListener(MouseEvent.CLICK,ChangeName);
}
private function ChangeName(e:MouseEvent):void {
    playerName.type = TextFieldType.INPUT;
    playerName.background = true;
    playerName.addEventListener(KeyboardEvent.KEY_DOWN,DoneEditing);
    stage.focus = playerName;
}
private function DoneEditing(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.ENTER) {
        // do your magic here
    }
}

Upvotes: 1

Related Questions