How do I programmatically associate a RadioButton with a RadioButtonGroup in ActionScript3? - apache-flex

I have a UI component that, for various reasons, I have to construct programatically. The component is a table of radio buttons grouped by column.
Right now, I'm constructing the column groups like so:
private function createGroupsForItemList(items: XMLList): void {
for each (var item: XML in items) {
var rbGroup: RadioButtonGroup = new RadioButtonGroup();
groups[item.#level.toString()] = rbGroup;
}
}
I'm trying to associate the RadioButton instances with the column groups like so:
private function createValueControl(item: XML): UIComponent {
var control: RadioButton = new RadioButton();
control.label = "";
control.group = groups[item.#level.toString()];
control.addEventListener(Event.SELECT, updateSelection);
return control;
}
I can see in the debugger that the control has an association to the group:
control.group == groups[item.#level.toString()]
However, I can see equally that the group does not know anything about the control:
group.radioButtons.length == 0
I imagine that this is because the setter for group in RadioButton is a dumb setter; all it does is copy to the variable, which doesn't do the magic that groupName does. However, I can't seem to find the value I should use to set the RadioButton.groupName property correctly.
So, in short, I'm stumped on how to get these bits to talk to each other. How do I do this?
-- EDIT --
It turns out that I can have the groups created and associated simply by setting the groupName property, but I can't get at the group to set up a selection listener; the group is NULL immediately after the setting process, which means that the second line below throws the Flex equivalent of an NPE:
control.groupName = groupNameForLevel(item);
control.group.addEventListener(Event.SELECT, updateSelection);

First instinct is that this issue has to do with invalidateDisplayList and when and how that is called. Of course, since issues related to that function are behind a number of Flex's quirks, I may just be scapegoating.
This is not the answer to your question per se, but it seems like it might actually work as an alternate solution.
RadioButtonGroups will initialize based on a IFlexDisplayObject. This means that you can do something like:
var c:HBox = new HBox();
var rbg:RadioButtonGroup = new RadioButtonGroup( c );
// do stuff with rbg.
c.addChild( new RadioButton() );
The problem is that it may not be the most practical answer, but it has the decided benefit of being a workable solution.

Setting groupName should work.
All I can suggest is to step through the group() getter of the RadioButton component and see where exactly it is failing. Are you programmatically creating the group too? If that's the case, maybe it isn't initialized fully yet.

Related

Flutter GetX variable changes but UI does not

I have two RxLists containing custom models:
var openDepartures = RxList<Departure>([]);
var finishedDepartures = RxList<Departure>([]);
I bind a stream to populate these RxLists with values from firebase. Since my Stream(which I am binding to the variables) changes according to the user's choice, I bind the new stream to the same variable, but since that would result in two streams controlling one variable, I "reset" the variable before that:
openDepartures = RxList<Departure>();
finishedDepartures = RxList<Departure>();
....
openDepartures.bindStream(
Database().getOpenDepartures(
userController.userLocation.value,
),
);
finishedDepartures.bindStream(
Database().getFinishedDepartures(
userController.userLocation.value,
),
);
The problem is that the UI is not refreshing, but when I do not "reset" the variables, everything works fine. What's weird as well is that the variable does get populated with the correct data. It is just not shown in the UI.
What I have tried to fix that:
update() method
Get.reloadAll()
call .refresh() on the variables
disposing and initializing the controller again
My question is now, how do I get the screen to refresh, or does anyone have an idea how to bind a new stream without "resetting" the old one and having multiple streams on one variable?
I finally solved my problem. The underlying problem was that I was binding multiple streams to one variable and therefore the variable was updated whenever one of the streams fired. The solution was the following:
Create an RxList of the variable:
final _openDepartureList = RxList<RxList<Departure>>();
Create a getter for the last element of that list:
RxList<Departure> get openDepartures => _openDepartureList.last;
Remove the old items:
if (_openDepartureList.length >= 2) {
_openDepartureList.removeRange(0, _openDepartureList.length - 1);
}
Add an empty RxList to the List
_openDepartureList.add(RxList.empty());
Bind the stream to the last element of the List, hence the one just added
_openDepartureList.last.bindStream():
That was it! I now always have the right stream bound to the variable I want and do not have multiple streams controlling one variable.
use update() like
void() { foo = newData; update(); }
or use ProgressIndicator
like
RxBool loading = false.obs
void Foo() { loading.value = true; your logic... loading.value = false; }
and use controller.loading.value in UI for check progress and show when loading is complete

datagrid cannot be found

I create each datagrid to be added to the NavigatorConent(), however, how do I retrieve the datagrid by ID so that I can point the ArrayCollection to datagrid's dataprovider?
private var pdg:String;
private function stabAdd():void {
var dg1:DataGrid = new DataGrid();
var cn:NavigatorContent = new NavigatorContent();
stab.addElement(cn);
cn.name = "nc"+nu;
dg1.id = "nc"+nu;
pdg = dg1.id;
dg1.addEventListener(MouseEvent.CLICK,cc);
nu++;
This will throw an error which pdg cannot be found, I wonder why:
trace(DataGrid(pdg));
The purpose of nu++ is to assign a
unique name (dg1, dg2, etc) to each
datagrid so that I can assign AC to
that datagrid's dataprovider
I can respect the need to give every component a unique name. The appropriate way to do that in ActionScript is not to specify the id/name field of the component, but rather to create an instance of the component as a variable. Something like this:
protected var myGrid : DataGrid;
And you can now access myGrid anywhere in the component, or in it's children, without creating some complicated scheme. If you need multiple DataGrid's you can store them in an array:
protected var myGridArray : Array = new Array();
And somewhere later in your code--probably createChildren() do something like this:
loop
var newGrid : DataGrid = new DataGrid()
myGridArray.push(newGrid);
end loop
For the most part, this is how all the Flex list based components do it with itemRenderers. They have an array of visible renderers.
As stated in #J_A_X_ comments, you are trying to convert pdg--a string--into a DataGrid. I would expect that to return a null value, as Flex casts tend to fail quietly.
If you want more help, you'll have to tell us the explicit error that you're receiving, possibly with line numbers and more code.

How to sort AdvancedDataGrid with hierarchical data?

I have an AdvancedDataGrid with a HierarchicalCollectionView as its dataProvider. When I view the grid with the dataset I'm working with, and click the header of the column I wish to sort on, everything works perfectly. It sorts it hierarchically exactly how I would expect it to.
What I want to do now is have the grid already be sorted when it is shown to the user. Is there a way to do this programatically? I can't for the life of me figure out how to do this, and clearly it's possible since the AdvancedDataGrid has this built in.
Edit - BTW, I've tried this:
var myData:HierarchicalCollectionView = new HierarchicalCollectionView(theDataSource);
// Works fine using only the line above and clicking the header to sort.
// This is the part that I tried adding:
var sort:Sort = new Sort();
sort.fields = [new SortField("startDate")];
myData.sort = sort;
myData.refresh();
This appears to do something as far as sorting goes, but it doesn't sort it in the same way as clicking the column header. "startDate" is a property of an object in theDataSource by the way.
Looks like you want to sort dates. Sort can't do that out of the box. You have to use a compareFunction.
If your objects are of type Date it's quite easy:
var sortField:SortField = new SortField("startDate");
sortField.compareFunction = ObjectUtil.dateCompare;
In case your column contains dates as strings you'll have to parse them first (code example from http://blog.flexexamples.com/2007/08/12/sorting-date-columns-in-a-datagrid/):
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
/* Date.parse() returns an int, but
ObjectUtil.dateCompare() expects two
Date objects, so convert String to
int to Date. */
var dateA:Date = new Date(Date.parse(itemA));
var dateB:Date = new Date(Date.parse(itemB));
return ObjectUtil.dateCompare(dateA, dateB);
}
var sortField:SortField = new SortField("startDate");
sortField.compareFunction = date_sortCompareFunc;
Then just use the sortField like you did in your example. That should work fine.
You can create a new advanced data grid sort event and dispatch it on the grid after the hierarchical data is set on it (unfortunately I've had to use a callLater to give the grid time to deal with the collection internally it seems assignments to the dataProvider of the ADG are sometimes asynchronous)
var advancedDataGridEvent : AdvancedDataGridEvent = new AdvancedDataGridEvent(AdvancedDataGridEvent.SORT, false, true);
advancedDataGridEvent.columnIndex = columnIndex;
advancedDataGridEvent.dataField = dataField;
dispatchEvent(advancedDataGridEvent);
This code is from an extension of ADG so you would want the dispatchEvent to actually be on your instance of the grid if you're not creating an extension.
Also a note from the code:
//setting sortDescending=true on a column does not work as expected. so, until a solution
//is found, this works just as well. the event that is dispatch just tells the column
//to reset. so, one resorts ascending (the default), while a second resorts descending.
//however, this second is only dispatched if defaultSortDesc is true on the grid.
if (defaultSortDesc)
{
dispatchEvent(advancedDataGridEvent);
}
It dispatches the event twice to flip the sort.

CheckBox header renderer with HierarchicalCollectionView

I've gotten a checkbox header renderer to work well with flat DPs, but a
hierarchical collection view is another story. On click, I want it to select all
checkboxes in a given column. Here is my code:
var dp:HierarchicalCollectionView = _dataGrid.dataProvider as
HierarchicalCollectionView;
var testDp:GroupingCollection = dp.source as GroupingCollection;
var rawDp:ArrayCollection = testDp.source as ArrayCollection;
for(var i:int=0 ; i < rawDp.length ; i++){
rawDp[i][_dataField] = cb.selected;
}
It selects all checkboxes on the 2nd level of data, but doesn't select the top
level of data. What am I missing here? I can't seem to find it.
Any tips are greatly appreciated. Thank you.
For hierarchical data you have to use a cursor which iterates over all levels of the hierarchical data.
var dp:IHierarchicalCollectionView = _dataGrid.hierarchicalCollectionView;
var cursor:IViewCursor= dp.createCursor();
while (!cursor.afterLast)
{
cursor.current[_dataField] = cb.selected;
cursor.moveNext();
}
Howerver, this works only with nodes that have previously been opened. So either expand all nodes with _dataGrid.expandAll() (you can collapse them afterwards since the nodes only have to be opened once) or iterate your hierarchical data manually:
function setCheckBoxValue(children:ArrayCollection, value:Boolean):void
{
for each (var child:Object in children)
{
if (child.hasOwnProperty("children") && child["children"])
setCheckBoxValue(child["children"], value);
child[_dataField] = value;
}
}
var myDataProvider:HierarchicalData = /* your data provider */;
// Call it like this...
setCheckBoxValue(myDataProvider.source, cb.selected);
Update: To answer your second question...
Create a new CheckBoxColumn which extends AdvancedDataGridColumn. You can use it to preconfigure your headerRenderer and itemRenderer.
In your custom item renderer you get hold of your column like this:grid = AdvancedDataGrid(listData.owner);
column = grid.columns[listData.columnIndex] as CheckBoxColumn;
Do the same in your header renderer.
Whenever the CheckBox value in one of your item renderers changes dispatch a event through your column. Something like: column.dispatchEvent(new Event("checkBoxValueChanged"));
Your header render should add an event listener to the column for the "checkBoxValueChanged" event (or whatever you call it). Whenever that event is fired loop through your data provider and update the headers CheckBox accordingly.
In theory that should work. HTH

Converting a string into a CheckBox

I have a string which is ultimately the id of a CheckBox.
What I need to be able to do is to access the CheckBox's properties from the string
var myCheckBox:Object;
var myString:String;
myString = "checkbox_1"
myCheckBox = Object(myString); ?!?!
... and then I'd need to get to myCheckBox.selected, and myCheckBox.label etc
easier answer:
if(this.hasOwnProperty(myString) && this[myString] is CheckBox) {
myCheckBox = this[myString] as CheckBox
}
It's a bit of overcoding (since the as keyword will return a null if it's not a checkbox and you could better handle it that way with potentially less code), but that should do ya.
Best of luck.
If you know what DisplayObjectContainer (e.g. Sprite, MovieClip) the CheckBox is inside you can use getChildByName.
Unfortunately if you are using Flex containers (like Group) there is no function getElementByName(). There is getElementAt so you could write a loop that iterates over all of a Groups elements until it encounters one that matches the name you have.

Resources