January 26, 2011

Setting a static background for a DataGroup

Hi guys, So… this is my first post for 2011, and a technical one. How sad, huh? Giving that we have a little less than 2 years for the great galactic alignment and the end of humanity, I thought it would be a great opportunity to display some code regarding a static background for the Spark DataGroup… yeah… oh well.

This is the thin - you would like to create a single DataGroup with an Item Renderer, but have it's content (the item renderer) spread on a background that will simulate different regions in it. get it? no? ok - what I mean is to have a background with 3 colors in it. this background is static and supplies the background for the item renderer's content.
Now, you can say: "why doing it like this, and not have the item renderer define it's background colors. Having multiple ones will create the illusion of a continuous background", right? Wrong. You will have the background just where you have data.
I want the whole list to have the same background, regardless of data. The idea of having 3 different lists combined was also an option, but I rejected it as being to expensive and, well, HTML-ish :). There must be a better way, right?

So, here how it goes:
<?xml version="1.0" encoding="utf-8"?>
            import mx.utils.UIDUtil;
            import mx.collections.ArrayCollection;
            import mx.events.FlexEvent;
            private var collection : ArrayCollection;
            protected function application1_creationCompleteHandler(event:FlexEvent):void {
                collection = new ArrayCollection();
                for ( var x:int = 0; x < 3; x++ ) {
                    collection.addItem( UIDUtil.createUID() );
            height="100%" >      
            <s:Rect width="100%" height="100%" >          
                        <s:SolidColor color="black"/>
                <s:Rect width="100%" height="50" bottom="0" >          
                        <s:SolidColor color="0xFFFF00" />
                <s:Rect width="100%" height="50" top="0" >          
                        <s:SolidColor color="0xFF0000" />
                    dataProvider="{ collection }"
                            <s:ItemRenderer width="100" height="100%" minHeight="200">
                                    <s:State name="normal" />
                                    <s:State name="hovered" />
                            useVirtualLayout="true" />

It’s based on a sample code I took from one of Adobe's demos , just to get the whole item renderer thingy fast. What you should be interested in is that the Scroller which usually wraps the DataGroup is now wrapping a Group inside of it. this Group holds 2 items: another group for the background and the DataGroup. Inside the inner Group I've created a background with Rects, nothing fancy, just for the sake of it. I wanted to maintain the background ratio even when the scrolling is on. This is pretty much it. hope it saves you some time. Cheers.