0

我有一个搜索和结果页面,我想在结果文本中突出显示搜索过的关键字。有人建议我为此使用 TextLine,但我无法弄清楚如何使其工作。我开始了一个简单的、可编译的虚拟应用程序,希望有人能给我一些关于如何继续的提示:

<?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>

有人有想法么?

干杯,巴兹

4

2 回答 2

1

感谢 Treur,但我找到了更好的方法:setFormatOfRange()

该函数基本上改变了 RichEditableText 组件中一系列字符的格式(背景/前景)。所以我要做的就是:

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++;
    }
}

干净的。

于 2010-06-01T16:34:52.507 回答
0

您可以在关键字周围放置简单的 html 标记,并使用 RichText 组件而不是 TextLine 组件来显示文本。

有关flex 中的 html 的更多信息,请参阅http://blog.flexexamples.com/2009/10/06/displaying-html-formatted-text-in-a-spark-richtext-control-in-flex-4/ 。

此外,要搜索应在字符串中突出显示的单词,请使用 String.replace 方法: http: //livedocs.adobe.com/flex/3/langref/String.html#replace()

于 2010-05-31T12:21:00.123 回答