How to Style Items in a Flex 4 Spark List

I’ve often heard it said that while Flex has a knack for making difficult tasks easy, it also has the same knack for making seemingly easy tasks difficult. While I agree that on occasion it seems that way up front, I usually find that the solution isn’t usually difficult, just difficult to find.

That was the case I found when recently working with the Spark List Component. Dynamically assigning an ArrayList as a Spark List’s data provider was a quick task and everything worked as expected. I was thrilled. Now I just had to tweak the spacing between the list items and I’d be finished. Easy, right? Ultimately the answer is yes. However, arriving at the solution took me a couple of hours!

The Spark List component automatically adds cool rollover and select effects. It also allows you to change rollover colors, set the width, and adjust the font size with simple attributes. What it doesn’t let you do so easily is set the spacing between list items. ( Note that I’m referring to a dynamically populated List, not one in which you define each item individually where you have the luxury of modifying the attributes of each item ).

Here’s some code to demonstrate the situation:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx=""
	preinitialize="preinitHandler(event)"  >
		import mx.collections.ArrayList;

		private var monthsList:ArrayList;

		protected function preinitHandler(event:FlexEvent):void {
			monthsList = new ArrayList(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"]);

	<s:List id="months" dataProvider="{monthsList}" />

The code above populates a Spark List with months. Very quick and easy! But now I want to close up the space between the months. Simple padding or gap attribute on the list, right? Nope. lineheight? No. Custom VerticalLayout? Uh uh. Google? Majority of results show examples where each item is defined manually…that doesn’t help either.

The answer it turns out is to define a custom ItemRenderer. This is used to tell the results how they should render when displayed. Common sense, right? And it’s pretty easy to do too:

<s:List id="months" dataProvider="{monthsList}" >
				<s:Label text="{data}" paddingTop="3" paddingBottom="3" fontSize="11" />

You can style the output any way you like by styling the label in the ItemRenderer. Note that if your data source contains multiple “fields” with property names, you’ll need to tweak the label text value slightly to reflect the property name of the value you’ll be displaying. So, instead of {data}, you would use something like {data.propertyName}.

Bonus tip: For reusability and flexibility you can define the the ItemRenderer as a separate MXML file and assign it to the itemRenderer property of the Spark List. Even better, you can add the Label style to a style sheet and use it throughout your application.