The following example shows how you can use the truncateToFit property in the Label control in Flex to truncate strings if they exceed a specified width. The label control will terminate the string with “…” and allow you to roll over the text and read the entire (non-truncated) text in a tool tip, as seen in the following snippet:

<mx:Label text="The quick brown fox jumped over the lazy dog."
        truncateToFit="true"
        maxWidth="200" />

Full code after the jump.

The following example displays three Label controls:
The first Label control (“default”), simply sets the text property and allows the Label control to size itself to match the length of the text.
The second Label control (“truncateToFit = false”) sets the truncateToFit property to false and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed and is cropped off. You can see a portion of a last character in the Label control and rolling over the text will not display a tool tip.
The third Label control (“truncateToFit = true”) sets the truncateToFit property to true and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed, but the text displays “…” at the end of the control. No partial characters are displayed and rolling over the text displays a tool tip showing the entire contents of the text string.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/01/26/truncating-text-in-the-flex-label-control-using-the-truncatetofit-property/ -->
<mx:Application name="Label_truncateToFit_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">
 
    <mx:String id="str">The quick brown fox jumped over the lazy dog.</mx:String>
 
    <mx:Form>
        <mx:FormItem label="default:">
            <mx:Label text="{str}" />
        </mx:FormItem>
        <mx:FormItem label="truncateToFit = false:">
            <mx:Label truncateToFit="false"
                    text="{str}"
                    maxWidth="200" />
        </mx:FormItem>
        <mx:FormItem label="truncateToFit = true:">
            <mx:Label truncateToFit="true"
                    text="{str}"
                    maxWidth="200" />
        </mx:FormItem>
    </mx:Form>
 
</mx:Application>

View source is enabled in the following example.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

22 Responses to Truncating text in the Flex Label control using the truncateToFit property

  1. Quentin says:

    A quick comment to add that ‘truncateToFit’ won’t show the ‘…’ ending string on HTML Labels. They only get truncated.

    Here what you can find in Label.as :

    // Plain text gets truncated with a "...".
    // HTML text simply gets clipped, because it is difficult
    // to skip over the markup and truncate only the non-markup.
    // But both plain text and HTML text gets an automatic tooltip
    // if the full text isn't visible.
  2. rob says:

    Hey folks, would anyone know how to extend the Label class, so that the tooltip is always shown when you hover over it? whether or not the label is truncated..

  3. Chris Brind says:

    @rob there’s a couple of ways I can think of. Inline:

    <mx:Label id="_alabel" text="hello" toolTip="{_alabel.text}" />
    

    secondly, you could subclass label and override the setter for the text property and assigning the text being set to the tooltip. i haven’t tried this, so this code is off the top of my head:

    public class TippedLabel extends Label {
    
      override public function set text(o:String) : void {
        super.text = o;
        super.toolTip = o;
      }
    
    }
    

    Hope that helps.

    Cheers,
    Chris

  4. Pat Long says:

    Is there a way of using truncateToFit AND getting the Label to wrap? It seems the only way to get truncateToFit is to set a MaxWidth but the only way I have found to get wrapping to work is to set width=100%

  5. mregert says:

    One possible solution would be:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    	<mx:Script>
    		<![CDATA[
    		import mx.utils.StringUtil;
    		[Bindable]
    		private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    		private var maxStringLength:int = 50;
    		private function truncatedString(source:String):String {
    			var shortString:String = StringUtil.trim(source);
    			shortString = shortString.substr(0, maxStringLength);
    			if (source.length != 0 && source.length > maxStringLength) {
    				shortString += "...";
    			}
    			return shortString;
    		}
    		]]>
    	</mx:Script>
    	<mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10">
    		<mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/>
    	</mx:Panel>
    
    </mx:Application>
    
  6. mregert says:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    	<mx:Script>
    		<![CDATA[
    		import mx.utils.StringUtil;
    		[Bindable]
    		private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    		private var maxStringLength:int = 50;
    		private function truncatedString(source:String):String {
    			var shortString:String = StringUtil.trim(source);
    			shortString = shortString.substr(0, maxStringLength);
    			if (source.length != 0 && source.length > maxStringLength) {
    				shortString += "...";
    			}
    			return shortString;
    		}
    		]]>
    	</mx:Script>
    	<mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10">
    		<mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/>
    	</mx:Panel>
    
    </mx:Application>
    
  7. Dinesh Copoosamy says:

    Is there a way to get truncated text to move left and right periodically so you can read the entire label?

  8. is there any way to customize the truncation indicator?

  9. John says:

    How to get flex to display the ‘…’ ending on truncated HTMLText labels:

    1. Place the HTMLText in an invisible label.

    <mx:Label id="lblSubcategoryHTML" htmlText="{topRec.subcategory}"
      width="0" height="0" visible="false"/>

    The invisible label will convert entity references (e.g. “õ”) to utf8. The text attribute has the result of the conversion.

    2. Set the text attribute of the label you want to show to the text attribute of the invisible label converter.

    <mx:Label width="210" text="{lblSubcategoryHTML.text}"/>
  10. Anne says:

    I’m having trouble with this truncateToFit thing: it seems as if Flex does’nt find the appropriate text (“…”) to use – it is always displaying the text cut off and adds “null” to its end instead. Maybe this is because I’m using a differend resource bundle for all my texts (i18n). Which key do I have to use to give the “…” text back to my Flex application? Does anyone know?
    Help is really appreciated.

  11. Ahmad says:

    Hey check this
    http://ahmadflex.wordpress.com/2009/05/28/flex-marquee-label/

    This component extends label. when text is truncated and you hover over the label it will keep scrolling to show all the text until mouse is out

    Ahmad

  12. Sohil says:

    Hey Anne ,

    Did you find answer to your question ?
    I m also stuck with same problem

    Thanks

    • Leandro says:

      Hi,

      Anne and Sohil,
      I had this problem too, I found a solution for me… maybe it works fo you…
      In the resourceManager.localeChain, I put two locales:

      resourceManager.localeChain = ['pt_BR', 'en_US'];

      Flex try to use the first locale, what is not found in the first, is used from the second

      (Sorry for my english)

      • Anne says:

        Inside the UITextField you can find the code:
        truncationIndicatorResource = resourceManager.getString(“core”, “truncationIndicator”);
        So I suppose this is missing within my application because I have my own resource bundle (named differently)…
        I will add one with the name “core” and add at least the missing “…” to it again.

        Best wishes

    • Shilpa says:

      I have seen the problem with appending null at the end. Seen it on Linux with flash player debug version 9. Once we upgraded to flash player debug version 10, that problem went away. It isn’t related to the locale stuff cos I dont even use any of the inbuilt locale flex provides.
      Hope this helps.
      Shilpa

  13. Adrian says:

    Perhaps slightly off topic:

    As far as I know, there is no way to prevent a button from truncating its text, and Adobe have closed the issue without fixing it:

    http://bugs.adobe.com/jira/browse/SDK-12992

    • Peter deHaan says:

      Adrian,

      I believe Adobe closed the enhancement as unable to reproduce. If you have a test that shows a truncated label where truncation shouldn’t be happening, can you please attach it to that bug?

      For example, the following example shows a button label that does not truncate itself:

      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
       
          <mx:Button label="The quick brown fox jumps over the lazy dog" />
       
      </mx:Application>

      As far as I know, a Button should not truncate its label unless you give the Button control an explicit width or set a left/right constraint. But if you have an example that shows otherwise, please attach it to the JIRA bug and Adobe can investigate.

      Thanks,
      Peter

  14. Anonymous says:

    Hi,

    I am facing an issue while scaling a Label with truncateToFit property as true. While zooming in/out, sometimes the text which is truncated is displayed without ellipses or 1 or 2 ellipses sometimes. I tried setting fontAntiAliasType=”animation” thinking that it might solve the issue.
    But it didnt :-(

    Please find the code below:

    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
        <mx:Script>
            <![CDATA[
                private function zoom():void
                {
                    c.scaleY = slider.value / 100;
                    c.scaleX = slider.value / 100;
                }
            ]]>
        </mx:Script>
        <mx:Canvas id="c" x="109" y="111" width="156" height="41" scaleX="0.5" scaleY="0.5">
            <mx:Label id="l1" x="28" y="10" text="Labelgettingtruncatedddddddddd" width="100" truncateToFit="true" fontAntiAliasType="animation"/>
        </mx:Canvas>
        <mx:VSlider id = "slider"
                    minimum = "5"
                    maximum = "200"
                    value = "100"
                    snapInterval = ".001"
                    liveDragging = "true"
                    change = "zoom();"/>
    </mx:Application>

    Could anyone of you help me finding whats going wrong here?

    Thanks in Advance,Srilatha

  15. walv says:

    If you have width=”100%” and you need to have correct truncation on resize,
    use
    mx:Label
    truncateToFit=”true”
    text=”{str}”
    minWidth=”0″

  16. DevSachin says:

    It is not working, When i am binding text in mx:Label in flex 4. With .text property it is working fine.

    Any solution?

    Sachin Dev tripathi

  17. DevSachin says:

    example for previous comment
    %lt;mx:Label text={txtname}%gt;

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree