Setting an icon in a Button control

by Peter deHaan on July 21, 2007

in Button, Embed

There are two general methods for embedding an icon into a Button control. The first method involves creating a variable in the Flex application, and using the [Bindable] and [Embed] meta data. You specify the path to the icon in the source parameter of the Embed meta data and then to use the icon in a Button, you use data binding, which in this case would look like icon="{Icon}". The second method, embeds the icon inline in the Button tag itself, by using @Embed() and specifying the path to the image file as a parameter. See the full code after the jump.

Download source (ZIP, 2K) | View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/07/21/setting-an-icon-in-a-button-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            [Bindable]
            [Embed(source="assets/bug.png")]
            private var Icon:Class;
        ]]>
    </mx:Script>

    <mx:Button label="[Embed(source='assets/bug.png')]"
            icon="{Icon}" />
    <mx:Button label="@Embed('assets/bug.png')"
            icon="@Embed('assets/bug.png')" />

</mx:Application>

View source enabled in the following example.

{ 5 comments… read them below or add one }

1 Vit May 21, 2008 at 6:42 am

I guess is it possible to set button’s icon on the fly by actionscript? without having embed icon class defined?

can’t find the right way for this (

Reply

2 peterd May 21, 2008 at 7:11 am

Vit,

Check out Ben Stucki’s IconUtility component, “IconUtility Component for Dynamic Run-Time Icons”.

Peter

Reply

3 Lead Bi March 6, 2009 at 11:41 am

Thanks for sharing this example on embedding image inside of a button.

I was wondering if there is a quick way (or not so quick — but a way) of scaling down the source image.

Thanks
Lead

Reply

4 Cássio F. Oliveira April 24, 2009 at 2:07 am

The image fits inside the button… So everything you’ve gotta do is to set the button’s height or width.

Reply

5 adam November 26, 2009 at 3:52 am

cool !!!!!!!!!!!!!!!!!!!!!!!!!!!!

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can 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

Previous post:

Next post: