接下来的例子演示了Flex中创建一个简单计算器。严格来说这个还不能算是计算器,只是简单的计算了增加百分比的计算。在“Amount”中输入数字并拖动滑标,可以看到计算结果。
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
private function updateTotal():void {
var amt:Number = parseFloat(amount.data.toString());
if (isNaN(amt)) {
total.text = "Not a Number";
return;
}
var tipAmt:Number = amt * tip.value/100;
total.text = currencyFormatter.format(tipAmt + amt);
}
private function dataTipFunc(item:Number):String {
var amt:Number = parseFloat(amount.data.toString());
var tipAmt:Number = amt * item/100;
return item + "% (" + currencyFormatter.format(tipAmt) + ")";
}
private function amount_focusOut(evt:FocusEvent):void {
amount.data = Number(amount.text).toFixed(2);
amount.text = currencyFormatter.format(amount.data);
}
private function amount_focusIn(evt:FocusEvent):void {
amount.text = amount.data.toString();
}
]]>
</mx:Script>
<mx:CurrencyFormatter id="currencyFormatter" precision="2" />
<mx:Form>
<mx:FormHeading label="Tip Calculator" />
<mx:FormItem label="Amount:">
<mx:TextInput id="amount"
data="0"
restrict="0-9."
change="updateTotal();"
focusOut="amount_focusOut(event);"
focusIn="amount_focusIn(event);" />
</mx:FormItem>
<mx:FormItem label="Tip:">
<mx:HSlider id="tip"
minimum="0"
maximum="30"
value="15"
labels="[0,5,10,15,20,25,30]"
snapInterval="1"
tickInterval="5"
liveDragging="true"
change="updateTotal();"
showTrackHighlight="true"
dataTipFormatFunction="dataTipFunc" />
</mx:FormItem>
<mx:FormItem label="Total:" fontWeight="bold">
<mx:Label id="total" />
</mx:FormItem>
</mx:Form>
</mx:Application>
Flex中创建一个简单计算器的例子