Flex: how to get the real objects width?
when I check the width of my objects I always get 0. Here is an example:
newTag = new LinkButton();
newTag.label = dataManager.tagViewTimelineModel.tags.getItemAt(i).name;
newTag.setStyle("color","#FFA500");
newTag.setStyle("rollOverColor","#FFA500");
newTag.setStyle("selectionColor","#CCCCCC");
newTag.toolTip ="Unselect tag";
newTag.setStyle("fontSize",16);
Alert.show(newTag.width); //This is 0
I guess because width is a property I can set, but it is not automatically computed by Flex. How can I know how big are my obj开发者_C百科ects (as conseguence of the included text ?)
thanks
Flex does automatically compute width, however it's set during the Flex Component Lifecycle, so it isn't always available immediately after creating a component.
You'll want to read up on the component lifecycle: http://livedocs.adobe.com/flex/3/html/help.html?content=ascomponents_advanced_2.html
http://flexcomps.wordpress.com/2008/05/09/flex-component-life-cycle/
And in particular, with text fields, flex tends to behave a bit oddly, you may need to use textWidth, rather than width, or force a call to validateNow() to make sure it's measured, but you'll want to use that technique sparingly and carefully. http://www.colettas.org/?p=89
In general, you need to wait until the component lifecycle calls 'measure' to get the component's width, and any layout you do w/ this width should be done in updateDisplayList() rather than immediately after the components is created.
The sizing and positioning of a component is always set by that component's parent. In your code you have not yet added the LinkButton to a container, and therefore it will not yet have a size. Width and Height will always be zero in such a case.
Once you add it as a child to a parent, it will start through the component lifecycle. It will call mesaure() will define it's measuredHeight and measuredWidth values. It is up to the parent to decide whether to use the measuredHeight or measuredwidth or not. This is usually done in updateDisplayList().
If you're using a default Flex container, it probably already has methods to size it's children; and you only have to worry about adding it as a child.
However, keep in mind the lifecycle has to run before it will have width or height. You can't addChild and immediately expect non-zero values.
yap that's right. The width of the component WILL be computed after you set the text - it just takes to the next screen update. What you could do is to is:
private function showWidth():void {
Alert.show(newTag.width);
}
callLater(showWidth);
The "callLater()"-Method postpones a call to a function until the next screen update.
Hope this helps
精彩评论