Flex中实现自定义ToolTip,也很简单,只要按如下三个步骤即可:
1.容器类实现mx.core.IToolTip接口,如下:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.core.IToolTip"
width="240"
alpha=".2"
borderThickness="2"
backgroundColor="#A4A4A4"
dropShadowEnabled="true"
borderColor="black"
borderStyle="solid"
roundedBottomCorners="true"
cornerRadius="10"
horizontalAlign="center"
height="80"
verticalAlign="middle">
<mx:Script><![CDATA[
[Bindable]
public var staName:String = "";
[Bindable]
public var percentage:String = "";
// Implement required methods of the IToolTip interface; 接口需要实现的方法 必须写!
public var _text:String;
[Bindable]
public function get text():String {
return _text;
}
public function set text(value:String):void {
}
]]></mx:Script>
<mx:HBox x="0" y="0" width="100%" height="100%" verticalAlign="top">
<mx:Label text="{staName}" width="30%" id="lbl_staName" textAlign="center"/>
<mx:Image width="30%" source="@Embed(source='../../../../Images/fltIcon.PNG')" horizontalAlign="right"/>
<mx:Label text="{percentage}" width="20%" id="lbl_percentage" textAlign="center"/>
</mx:HBox>
</mx:Panel>
2.要实现动态加载ToolTip,需要设置ToolTip载体控件的事件,例如:
var tmpDisplay:DisplayObject= this.getChildByName(s) as DisplayObject;
//绑定提示卡
tmpDisplay.toolTip=" "; //注意一定要设置此属性 否则无法显示
tmpDisplay.addEventListener(ToolTipEvent.TOOL_TIP_CREATE,function (event:ToolTipEvent):void{createCustomTip('邯郸','80%',event)});
tmpDisplay.addEventListener(ToolTipEvent.TOOL_TIP_SHOW,function (event:ToolTipEvent):void{positionTip(event)});
tmpDisplay.addEventListener(ToolTipEvent.TOOL_TIP_END,function (event:ToolTipEvent):void{onToolTipEnd(event)});
3.完成ToolTip创建、显示、销毁的三个方法:
//创建提示卡
private function createCustomTip(staName:String, percentage:String, event:ToolTipEvent):void {
stt.styleName="StationToolTipStyle1";
stt.staName = staName;
stt.percentage=percentage;
event.toolTip = stt;
}
//确定位置 此方法完成显示坐标的设置,如果设置不正确 可能会引发频繁调用
private function positionTip(event:ToolTipEvent):void{
//由于诸多点 都放在了Canvas之上 所以要受Canvas坐标影响 使用localToGlobal方法做转换
var objSource:DisplayObject=event.currentTarget as DisplayObject;
var pt:Point = new Point();
pt.x = 0;
pt.y = 0;
pt = objSource.localToGlobal(pt); //受Canvas坐标影响 使用localToGlobal方法做转换
event.toolTip.x=pt.x + objSource.width+ 10;
event.toolTip.y=pt.y-objSource.height/2;
/*如果没有Canvas(也就是父容器)影响的话 可以直接设置坐标
event.toolTip.x=event.currentTarget .x + event.currentTarget .width+ 10;
event.toolTip.y=event.currentTarget .y-event.currentTarget .height/2;
*/
}
//隐藏后销毁
private function onToolTipEnd(event:ToolTipEvent):void
{
var ttip:StationToolTip = event.toolTip as StationToolTip;
ToolTipManager.destroyToolTip(ttip);
ttip = null;
}
用此三招,建立动态绑定的自定义ToolTip,无往而不胜!