views:

355

answers:

2

I have a search and results page that I would like to highlight the keywords that were searched for, in the text of the results. It was suggested that I use TextLine for this, but I am having trouble figuring out how to make it work. I started a simple, compilable dummy application and was hoping someone could give me some tips on how to continue:

<?xml version="1.0" encoding="utf-8"?>
<s:Application
 xmlns:fx="http://ns.adobe.com/mxml/2009"
 xmlns:s="library://ns.adobe.com/flex/spark"
 xmlns:mx="library://ns.adobe.com/flex/mx"
 initialize="initApp();">

 <fx:Script>
  import flash.display.Sprite;
  import flash.text.engine.*;

  private var textLine:TextLine;

  private function initApp():void {

   var normalFormat:ElementFormat = new ElementFormat(null, 12, 0x000000);
   var highlightFormat:ElementFormat = new ElementFormat(null, 14, 0xff0000);

   var textBlock:TextBlock = new TextBlock(new TextElement("This is text that has KEYWORDS. I would like to highlight these KEYWORDS by changing their font color and adding a light yellow background graphic.", normalFormat)); 

   textLine = textBlock.createTextLine();
   textLine.y = 100;

   embeddedFontHolder.addChild(textLine); 
  }
 </fx:Script>

 <mx:UIComponent width="100%" id="embeddedFontHolder" />
</s:Application>

Anyone have any ideas?

Cheers, Baz

A: 

You could place simple html tags around the keywords and display the text with a RichText component instead of a TextLine component.

See http://blog.flexexamples.com/2009/10/06/displaying-html-formatted-text-in-a-spark-richtext-control-in-flex-4/ for more info about html in flex.

Furthermore, to search for words that should be highlighted in a string, use the String.replace method: http://livedocs.adobe.com/flex/3/langref/String.html#replace()

Treur
A: 

Thanks Treur, but I found an even better way: setFormatOfRange()

That function basically changes the format (background/foreground) of a range of characters in a RichEditableText component. So all I have to do is:

var highlightFormat:TextLayoutFormat = new TextLayoutFormat();
highlightFormat.backgroundColor = 0xffee66;

var keywordsArray:Array = model.keywords.toLowerCase().split(' ');
var indexOfKeyword:int = 0;
for each (var currentKeyword:String in keywordsArray) {
    while((indexOfKeyword = this.text.toLowerCase().indexOf(currentKeyword, indexOfKeyword)) >= 0) {                
        this.setFormatOfRange(highlightFormat, indexOfKeyword, indexOfKeyword + currentKeyword.length);
        indexOfKeyword++;
    }
}

Clean.

Baz
Hmm. I didn't know that. However, I personally think you are better of using css, because now you have to change the action-script class to change the style of the highlighted words. With css, you have a more clear separation of UI logic and UI format.
Treur