Posts Tagged ‘RadioButtonGroup’

Simplify radio button usage with a RadioButtonBox component

// July 16th, 2009 // No Comments » // Flex framework

This post is about the tiny implementation of a RadioButtonBox component which simplifies the usage of radio buttons in Flex applications.

You can insert the RadioButtonBox component wherever you want in your application, add radio buttons within it and read the value property of the RadioButtonBox to know which value is selected.

Here follows an MXML usage example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:wg="com.webgriffe.components.*">
 
  <mx:Script>
  <![CDATA[
    import mx.controls.Alert;
  ]]>
  </mx:Script>
 
  <wg:RadioButtonBox id="group" direction="horizontal">
    <mx:RadioButton label="uno" />
    <mx:RadioButton label="due" />
    <mx:RadioButton label="tre" />
  </wg:RadioButtonBox>
 
  <mx:Button label="test" 
      click="Alert.show('Selected value: ' + group.value)" />
 
</mx:Application>

The source code of the RadioButtonBox is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.webgriffe.components
{
import flash.display.DisplayObject;
 
import mx.containers.Box;
import mx.controls.RadioButton;
import mx.controls.RadioButtonGroup;
 
public class RadioButtonBox extends Box
{
  // -------------------------------------------------------------------------
  //
  // Properties 
  //      
  // -------------------------------------------------------------------------
 
  private var _group:RadioButtonGroup;
 
  public function get value():Object
  {
    return _group.selectedValue;
  }
 
  // -------------------------------------------------------------------------
  //
  // Constructor 
  //      
  // -------------------------------------------------------------------------
 
  public function RadioButtonBox()
  {
    super();
 
    _group = new RadioButtonGroup();
  }
 
  // -------------------------------------------------------------------------
  //
  // Overridden Methods 
  //      
  // -------------------------------------------------------------------------
 
  override public function addChild(child:DisplayObject):DisplayObject
  {
    if (child is RadioButton)
    {
      RadioButton(child).group = _group;
    }
 
    return super.addChild(child);
  }
 
}
}

Enjoy!