Always displaying the selected text in a TextInput in Flex

The following example shows how you can get the Flex TextInput control to display the currently selected text regardless of whether it has focus by using the mx_internal namespace, the getTextField() method and the Boolean alwaysShowSelection property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/04/30/always-displaying-the-selected-text-in-a-textinput-in-flex/ -->
<mx:Application name="TextInput_getTextField_alwaysShowSelection_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.core.UITextField;
            import mx.controls.TextInput;

            private function init(evt:Event):void {
                var ti:TextInput = evt.currentTarget as TextInput;
                var tf:UITextField = ti.mx_internal::getTextField();
                tf.alwaysShowSelection = true;
            }
        ]]>
    </mx:Script>

    <mx:TextInput id="textInput"
            text="The quick brown fox jumps over the lazy dog."
            selectionBeginIndex="4" selectionEndIndex="9"
            initialize="init(event);" />
    <mx:Button label="Submit" />

</mx:Application>

View source is enabled in the following example.

One thought on “Always displaying the selected text in a TextInput in Flex

Comments are closed.