需求是这样的,需要批处理一些信息条目,每条信息有相应的radiobutton,选是还是否操作。由于要求的样式比较花俏,用datagrid无法满足,就考虑用repeater来做。关于radiobutton的样式,能想到的如下(每组radiobutton点选互不影响):
<mx:HBox>
<mx:RadioButtonGroup id="group"/>
<mx:RadioButton group="group" id="yes"/>
<mx:RadioButton group="group" id="no"/>
</mx:HBox>定义一个群组id,单个radiobutton指定群组id,而后用repeater组件进行循环。对于一般组件,如Label、Text等,定义了id进行repeater是不会出问题的,但是对于RadioButtonGroup ,会报如下错误:
Unable to generate initialization code within Repeater, due to id or data binding on a component that is not a visual child.
在网上搜索了一下,对于radiobutton使用repeater的人,都有这个疑惑,后来总算在英文网站是找了一个解决办法,如下文:
http://www.jonathanrowny.com/journal/radiobuttongroup-inside-repeater
原理是根据数据源大小生成一个radiobuttongroup数组,而后repeater的时候,根据repeater的index从该数组中取相应的group绑定到radiobutton,实现radiobutton各组操作分离,互不影响。
在此基础上,做了一个扩展实例,模拟演示,可以初始得到每组radiobutton的初始值,以及点击时,可以分别得到每组radiobutton的值。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.controls.Alert; import mx.controls.RadioButtonGroup; import mx.controls.RadioButton; import mx.controls.Label; import mx.collections.ArrayCollection; [Bindable] private var rbGroups:ArrayCollection; [Bindable] public var myArray:Array=[{男: "yes", 女: "no"}, {男: "yes", 女: "no"}, {男: "no", 女: "yes"}, {男: "no", 女: "yes"}]; /** * 通过数组初始值,判断选择。 */ private function isSelect(item:Object):Boolean { if (item.男 == "yes") { return true; } else { return false; } } /** * 根据数据源建立一个radiobuttongroup组 */ private function createRBGroups():void { rbGroups=new ArrayCollection(); var rbGroup:RadioButtonGroup; for each (var item:Object in someRepeater.dataProvider as ArrayCollection) { rbGroup=new RadioButtonGroup(); rbGroups.addItem(rbGroup); } } /** * 单击某组radiobutton,显示相应值 */ private function showSex(event:Event):void { var radio:RadioButton=event.currentTarget as RadioButton; event.currentTarget.parent.parent.getChildByName("sexShow").text="This is a " + radio.label; } /** * 单击某组radiobutton,显示相应值 */ private function showDefault(item:Object):String { if (item.男 == "yes") { return "男"; } else { return "女"; } } ]]> </mx:Script> <mx:Panel width="100%" height="500"> <mx:Repeater repeatStart="createRBGroups()" id="someRepeater" dataProvider="{myArray}"> <mx:VBox> <mx:HBox> <mx:RadioButton id="male" group="{RadioButtonGroup(rbGroups.getItemAt(someRepeater.currentIndex))}" label="男" selected="{isSelect(someRepeater.currentItem)}" click="{showSex(event)}"/> <mx:RadioButton id="female" group="{RadioButtonGroup(rbGroups.getItemAt(someRepeater.currentIndex))}" label="女" selected="{!isSelect(someRepeater.currentItem)}" click="{showSex(event)}"/> </mx:HBox> <mx:Label id="sexShow" width="120" text="This is a {showDefault(someRepeater.currentItem)}"/> </mx:VBox> <mx:HRule width="100%"/> </mx:Repeater> </mx:Panel> </mx:Application>
示例如下图
Flex RadioButton 分组使用repeater
最新推荐文章于 2021-11-08 10:55:32 发布