Как сделать встроенное графическое изображение интерактивным в TextFlow

Я пытаюсь сделать изображение кликабельным в TLF TextFlow, и, похоже, ничего не работает. Я добавил прослушиватель событий для события click, установил для buttonMode значение true и даже установил useHandCursor.

Вот мой код до сих пор:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       xmlns:utils="com.flexcapacitor.utils.*" 
                       width="1000" height="550" 
                       applicationComplete="init()" >

    <fx:Script>
        <![CDATA[
            import spark.utils.TextFlowUtil;

            import flashx.textLayout.edit.IEditManager;
            import flashx.textLayout.edit.SelectionState;
            import flashx.textLayout.elements.InlineGraphicElement;
            import flashx.textLayout.elements.TextFlow;
            import flashx.textLayout.formats.TextLayoutFormat;

            static private const simpleText:String = "<TextFlow xmlns='http://ns.adobe.com/textLayout/2008'>"
                + "<p styleName='center'><span typeName='a'>There are many </span><span styleName='italic'>such</span><span> lime-kilns </span><a href='http://www.google.com' typeName='a'><span>links</span></a><span> in that tract of country, for the purpose of burning the white marble which composes a large part of the substance of the hills. Some of them, built years ago, and long deserted, with weeds growing in the vacant round of the interior, which is open to the sky, and grass and wild-flowers rooting themselves into the chinks of the stones, look already like relics of antiquity, and may yet be overspread with the lichens of centuries to come. Others, where the lime-burner still feeds his daily and nightlong fire, afford points of interest to the wanderer among the hills, who seats himself on a log of wood or a fragment of marble, to hold a chat with the solitary man. It is a lonesome, and, when the character is inclined to thought, may be an intensely thoughtful occupation; as it proved in the case of Ethan Brand, who had mused to such strange purpose, in days gone by, while the fire in this very kiln was burning.</span></p>"
                + "<br/><p><span>The man who now watched the </span><span id='bold'>fire</span><span> was of a </span><span typeName='foo'>different</span><span> order, and troubled himself with no thoughts save the very few that were requisite to his business. At frequent intervals, he flung back the clashing weight of the iron door, and, turning his face from the insufferable glare, thrust in huge logs of oak, or stirred the immense brands with a long pole. Within the furnace were seen the curling and riotous flames, and the burning marble, almost molten with the intensity of heat; while without, the reflection of the fire quivered on the dark intricacy of the surrounding forest, and showed in the foreground a bright and ruddy little picture of the hut, the spring beside its door, the athletic and coal-begrimed figure of the lime-burner, and the half-frightened child, shrinking into the protection of his father's shadow. And when again the iron door was closed, then reappeared the tender light of the half-full moon, which vainly strove to trace out the indistinct shapes of the neighboring mountains; and, in the upper sky, there was a flitting congregation of clouds, still faintly tinged with the rosy sunset, though thus far down into the valley the sunshine had vanished long and long ago.</span></p>"
                + "</TextFlow>";

            private function init():void {
                var textFlow:TextFlow;

                TextFlow.defaultConfiguration.unfocusedSelectionFormat = TextFlow.defaultConfiguration.focusedSelectionFormat;
                TextFlow.defaultConfiguration.inactiveSelectionFormat = TextFlow.defaultConfiguration.focusedSelectionFormat;

                textFlow = TextFlowUtil.importFromString(simpleText);

                // set it into the editor
                editor.textFlow = textFlow;
            }

            public var imageElementsDictionary:Dictionary = new Dictionary(true);

            /**
             * Insert an image
             * 
             * source is either 
             *    a String interpreted as a URI, 
             *    a Class interpreted as the class of an Embed DisplayObject, 
             *    a DisplayObject instance or 
             *    a URLRequest.
             * width, height is a number or percent
             * options - none 
             */
            public function insertImage(source:Object, width:Object = null, height:Object = null, operationState:SelectionState = null):InlineGraphicElement {
                var inlineGraphicElement:InlineGraphicElement;
                var currentFormat:TextLayoutFormat;
                var selectionStart:int;
                var selectionEnd:int;
                var loader:Loader;
                var displayObject:DisplayObject;
                var textFlow:TextFlow;

                if (editor && editor.textFlow && editor.textFlow.interactionManager is IEditManager) {
                    textFlow = editor.textFlow;

                    if (editor.selectionActivePosition==-1) {
                        textFlow.interactionManager.selectFirstPosition();
                    }

                    inlineGraphicElement = IEditManager(textFlow.interactionManager).insertInlineGraphic(source, width, height, null, operationState);
                    //inlineGraphicElement.status = InlineGraphicElementStatus.LOADING;
                    loader = inlineGraphicElement.graphic as Loader;
                    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, inlineGraphicElementLoader_complete);
                    loader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
                    displayObject = loader.parent;

                    imageElementsDictionary[displayObject] = inlineGraphicElement;

                    IEditManager(editor.textFlow.interactionManager).updateAllControllers();

                }

                return inlineGraphicElement;
            }

            /**
             * Handle inline graphics loaded
             * */
            public function inlineGraphicElementLoader_complete(event:Event):void {
                var loader:Loader = event.currentTarget.loader as Loader;
                var displayObject:DisplayObject = loader.parent;
                var sprite:Sprite = displayObject as Sprite;
                var inlineGraphicElement:InlineGraphicElement;

                inlineGraphicElement = imageElementsDictionary[displayObject];

                if (sprite) {
                    sprite.buttonMode = true;
                }

                if (displayObject) {
                    displayObject.addEventListener(MouseEvent.CLICK, inlineGraphicElementClickHandler, false, 0, true);
                }

            }

            protected function inlineGraphicElementClickHandler(event:Event):void {
                trace ("Clicked");
            }

            private function uncaughtErrorHandler(event:UncaughtErrorEvent):void {
                trace ("Error");

                if (event.error is Error) {
                    var error:Error = event.error as Error;
                    // do something with the error
                }
                else if (event.error is ErrorEvent) {
                    var errorEvent:ErrorEvent = event.error as ErrorEvent;
                    // do something with the error
                }
                else {
                    // a non-Error, non-ErrorEvent type was thrown and uncaught
                }
            }
        ]]>
    </fx:Script>


    <s:Button label="Insert Image" top="0" horizontalCenter="0"
              click="insertImage('http://www.radii8.com/r8m/wp-content/uploads/2015/10/radiate-logo-2.png')"/>

    <s:RichEditableText id="editor" text="Some rich text" 
                        top="100" left="100"
                        width="600"/>

</s:WindowedApplication>

1 ответ

В следующем коде менеджер курсора используется для отображения курсора руки, когда он находится над встроенными графическими элементами. Есть несколько строк ссылок на локальные классы, которые вам нужно будет удалить, чтобы запустить этот пример кода.

ПРИМЕЧАНИЕ: я вставил пример кода здесь, но достиг предела количества символов, так что вот пастбин. Я могу создать меньший пример.

Другие вопросы по тегам