March 16th, 2007 by Kyle
Tags: ActionScript, combobox, components, Flex, mxml
Posted in: Flex
I wrote a simple little extension to ComboBox to allow the dropdown to expand to the width of the widest entry and the ComboBox input to expand/contract to the width of the selected item. This is based on the simple ComboBox sample from the docs found here.
Here is the source code for the component:
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()" change="onChange(event);">
<mx:Script>
<![CDATA[
import mx.controls.ComboBase;
import mx.core.EdgeMetrics;
private function init():void{
this.dropdownWidth=calculatePreferredSizeFromData(this.dataProvider.length).width;
}
private function onChange(e:Event):void{
var txt:String = itemToLabel(selectedItem);
if(measureText(txt).width > 0){
var buttonWidth:Number = getStyle("arrowButtonWidth");
// Text fields have 4 pixels of white space added to each side
// by the player, so fudge this amount.
// If we don’t have any data, measure a single space char for defaults
var bm:EdgeMetrics = borderMetrics;
var textWidth:Number = measureText(txt).width + bm.left + bm.right + 8;
this.width = textWidth + buttonWidth;
}
else {
this.width=DEFAULT_MEASURED_MIN_WIDTH
}
}
]]>
</mx:Script>
</mx:ComboBox>
Here is the source for the app:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*">
<mx:Script>
<![CDATA[
[Bindable]
public var cards: Array = [ {label:"Visa", data:1},
{label:"MasterCard", data:2}, {label:"American Express", data:3} ];
[Bindable]
public var selectedItem:Object;
]]>
</mx:Script>
<mx:Panel title="ComboBox Control Example"
height="75%" width="75%" layout="horizontal"
paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10">
<ExpandoComboBox dataProvider="{cards}" width="75"
close="selectedItem=ExpandoComboBox(event.target).selectedItem"/>
<mx:VBox width="250">
<mx:Text width="200" color="blue" text="Select a type of credit card."/>
<mx:Label text="You selected: {selectedItem.label}"/>
<mx:Label text="Data: {selectedItem.data}"/>
</mx:VBox>
</mx:Panel>
</mx:Application>
Here is a link to the Flex Builder 2.0.1 project zip file that contains everything.










