Programmatically selecting text in an FxTextArea control in Flex Gumbo

The following example shows how you can use ActionScript to select text in a Flex Gumbo FxTextArea control by calling the setSelection() method. This example also shows how you can determine the current text selection’s anchor position and active position by using the selectionAnchorPosition and selectionActivePosition properties.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/11/16/programmatically-selecting-text-in-an-fxtextarea-control-in-flex-gumbo/ -->
<Application name="FxTextArea_setSelection_test"
        xmlns="http://ns.adobe.com/mxml/2009"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.events.SliderEvent;

            private function slider_change(evt:SliderEvent):void {
                var anchorIdx:uint = slider.values[0];
                var activeIdx:uint = slider.values[1];
                textArea.setSelection(anchorIdx, activeIdx);
            }

            private function textArea_selectionChange(evt:FlexEvent):void {
                var anchorIdx:uint = textArea.selectionAnchorPosition;
                var activeIdx:uint = textArea.selectionActivePosition;
                slider.values = [anchorIdx, activeIdx];
            }
        ]]>
    </Script>

    <ApplicationControlBar dock="true">
        <Form styleName="plain">
            <FormItem label="setSelection():">
                <HSlider id="slider"
                        minimum="0"
                        maximum="{textArea.text.length}"
                        thumbCount="2"
                        snapInterval="1"
                        liveDragging="true"
                        allowThumbOverlap="true"
                        showTrackHighlight="true"
                        change="slider_change(event);" />
            </FormItem>
            <FormItem label="selectionAnchorPosition:">
                <Label text="{textArea.selectionAnchorPosition}" />
            </FormItem>
            <FormItem label="selectionActivePosition:">
                <Label text="{textArea.selectionActivePosition}" />
            </FormItem>
        </Form>
    </ApplicationControlBar>

    <FxTextArea id="textArea"
            text="The quick brown fox jumps over the lazy dog"
            selectionVisibility="always"
            unfocusedSelectionColor="0xFF0000"
            selectionChange="textArea_selectionChange(event);" />

</Application>

One thought on “Programmatically selecting text in an FxTextArea control in Flex Gumbo

Comments are closed.