Spark.Components.List with variable content: Flex 4, AS3 - actionscript-3

I coded the following in Flex 4/AS3 and it doesn't worked as expected.
So, I would like to know if there is something wrong with my code... I'll explain it:
TileTest.mxml
<s:Application minWidth="955" minHeight="600" creationComplete="createButtons()"
<fx:Script>
<![CDATA[
import Object.TestButton;
import mx.collections.ArrayList;
private var _names:Array = ["one", "two", "three"];
public function createButtons():void
{
var buttons:ArrayList = new ArrayList();
for(var a:int = 0; a < _names.length; a++)
{
var testButton:TestButton = new TestButton();
testButton.customName = _names[a];
buttons.addItem(testButton);
}
myList.dataProvider = buttons;
}
]]>
</fx:Script>
<s:VGroup gap="12" width="100%">
<s:Label text="Options" fontSize="18" fontWeight="bold" color="#333333" />
<s:List width="100%" height="100%" id="myList" itemRenderer="Object.TestButton" borderVisible="false">
<s:layout>
<s:TileLayout orientation="rows" columnWidth="290" rowHeight="90" columnAlign="left" horizontalGap="0" verticalGap="0" />
</s:layout>
</s:List>
</s:VGroup>
</s:Application>
This is my Application. Here, I have a List called myList, where I load some TestButtons. I set a name for each button inside the loop.
TestButton
<s:Group width="300" height="90" click="{ Alert.show(_name); }"
<fx:Script>
<![CDATA[
import mx.controls.Alert;
private var _name:String = "just a test...";
public function set customName(newName:String):void
{
_name = newName;
Alert.show(_name);
this.addEventListener(MouseEvent.MOUSE_OVER, function():void{ Alert.show(_name); });
}
]]>
</fx:Script>
<s:BorderContainer accentColor="#000000" width="100%" height="100%" />
</s:Group>
As you can see, I have three Alerts in this component... I did so we can understand the problem.
The first Alert occurs when I set the customName, which occurs in the Application, as already shown.
The second one should occur on Mouse_Over, as the event listener been added to the Group element.
And the third Alert should occur on Click in the Group element.
Now, if I run the resulting swf, I see all the three buttons in the screen and three Alerts, one for each set customName by the Application and it alerts the right name.
If I put the mouse over any button, it doesn't alert any message.
If I click any button, it alerts the default message set to the _name property, which is "just a test..."
I can't understand what is the problem, as I was expecting it to always alert the name set by the Application to each button. Also, I don't want to change the components... what I'm saying is that I would like to have a List and TestButtons with a private String inside.
If the problem is in these specific implementation, so I'll have no other way than change it...
Thank you all!

The problem is that you have a list of TestButtons in your data provider, instead of just plain data. Those buttons get created, and that is why you see the correct Alert messages.
So, then Flex sees a list with three items and therefore it creates three additional TestButtons to render the data in your list. But those TestButtons are completely new ones, with default values for its properties.
To fix this, it would be better if you had data only in your data provider ArrayList, and you would access it through the data property of your item renderer.

Related

as3 print a page with text, image and data grid [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have an AIR application.
I want to print a set of text, image and datagrid my document is like a report.
As datagrid has different heights, I don't know how to do.
Could you help me ?
Best regards
Here's an example from the docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/printing/FlexPrintJob.html
FormPrintFooter.mxml
<s:VGroup name="FormPrintFooter"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
width="60%"
horizontalAlign="right" >
<!-- Declare and initialize the product total variable. -->
<fx:Script>
<![CDATA[
[Bindable]
public var pTotal:Number = 0;
]]>
</fx:Script>
<s:Label text="Product Total: {pTotal}"/>
</s:VGroup>
FormPrintView.mxml
<!-- Custom control to print the Halo DataGrid control on multiple pages. -->
<s:VGroup name="FormPrintView"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns="*">
<fx:Script>
<![CDATA[
import mx.core.*;
// Declare and initialize the variables used in the component.
// The application sets the actual prodTotal value.
[Bindable]
public var pageNumber:Number = 1;
[Bindable]
public var prodTotal:Number = 0;
// Control the page contents by selectively hiding the header and
// footer based on the page type.
public function showPage(pageType:String):void {
if (pageType == "first" || pageType == "middle") {
// Hide the footer.
footer.includeInLayout = false;
footer.visible = false;
}
if (pageType == "middle" || pageType == "last") {
// The header won't be used again; hide it.
header.includeInLayout = false;
header.visible = false;
}
if (pageType == "last") {
// Show the footer.
footer.includeInLayout = true;
footer.visible = true;
}
//Update the DataGrid layout to reflect the results.
validateNow();
}
]]>
</fx:Script>
<!-- The template for the printed page, with the contents for all pages. -->
<s:VGroup width="80%" horizontalAlign="left">
<s:Label text="Page {pageNumber}"/>
</s:VGroup>
<FormPrintHeader id="header" />
<!-- The data grid. The sizeToPage property is true by default, so the last
page has only as many grid rows as are needed for the data. -->
<mx:PrintDataGrid id="myDataGrid" width="60%" height="100%">
<!-- Specify the columns to ensure that their order is correct. -->
<mx:columns>
<mx:DataGridColumn dataField="Index" />
<mx:DataGridColumn dataField="Qty" />
</mx:columns>
</mx:PrintDataGrid>
<!-- Create a FormPrintFooter control and set its prodTotal variable. -->
<FormPrintFooter id="footer" pTotal="{prodTotal}" />
</s:VGroup>
PrintDataGridExample.mxml
<!-- Main application to print a Halo DataGrid control on multiple pages. -->
<s:Application name="PrintDataGridExample.mxml"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
initialize="initData();">
<fx:Script>
<![CDATA[
import mx.printing.*;
import mx.collections.ArrayCollection;
import FormPrintView;
import mx.core.FlexGlobals;
// Declare variables and initialize simple variables.
[Bindable]
public var dgProvider:ArrayCollection;
public var footerHeight:Number = 20;
public var prodIndex:Number;
public var prodTotal:Number = 0;
// Data initialization.
public function initData():void {
// Create the data provider for the DataGrid control.
dgProvider = new ArrayCollection;
}
// Fill the dgProvider ArrayCollection with the specified items.
public function setdgProvider(items:int):void {
prodIndex=1;
dgProvider.removeAll();
for (var z:int=0; z<items; z++) {
var prod1:Object = {};
prod1.Qty = prodIndex * 7;
prod1.Index = prodIndex++;
prodTotal += prod1.Qty;
dgProvider.addItem(prod1);
}
}
// The function to print the output.
public function doPrint():void {
var printJob:FlexPrintJob = new FlexPrintJob();
if (printJob.start()) {
// Create a FormPrintView control as a child of the current view.
var thePrintView:FormPrintView = new FormPrintView();
FlexGlobals.topLevelApplication.addElement(thePrintView);
//Set the print view properties.
thePrintView.width=printJob.pageWidth;
thePrintView.height=printJob.pageHeight;
thePrintView.prodTotal = prodTotal;
// Set the data provider of the FormPrintView component's data grid
// to be the data provider of the displayed data grid.
thePrintView.myDataGrid.dataProvider = myDataGrid.dataProvider;
// Create a single-page image.
thePrintView.showPage("single");
// If the print image's data grid can hold all the provider's rows,
// add the page to the print job.
if (!thePrintView.myDataGrid.validNextPage) {
printJob.addObject(thePrintView);
}
// Otherwise, the job requires multiple pages.
else {
// Create the first page and add it to the print job.
thePrintView.showPage("first");
printJob.addObject(thePrintView);
thePrintView.pageNumber++;
// Loop through the following code until all pages are queued.
while (true) {
// Move the next page of data to the top of the print grid.
thePrintView.myDataGrid.nextPage();
thePrintView.showPage("last");
// If the page holds the remaining data, or if the last page
// was completely filled by the last grid data, queue it for printing.
// Test if there is data for another PrintDataGrid page.
if (!thePrintView.myDataGrid.validNextPage) {
// This is the last page; queue it and exit the print loop.
printJob.addObject(thePrintView);
break;
} else {
// This is not the last page. Queue a middle page.
thePrintView.showPage("middle");
printJob.addObject(thePrintView);
thePrintView.pageNumber++;
}
}
}
// All pages are queued; remove the FormPrintView control to free memory.
FlexGlobals.topLevelApplication.removeElement(thePrintView);
}
// Send the job to the printer.
printJob.send();
}
]]>
</fx:Script>
<s:Panel title="DataGrid Printing Example"
width="75%" height="75%"
horizontalCenter="0" verticalCenter="0">
<s:VGroup left="10" right="10" top="10" bottom="10">
<mx:DataGrid id="myDataGrid" dataProvider="{dgProvider}">
<mx:columns>
<mx:DataGridColumn dataField="Index"/>
<mx:DataGridColumn dataField="Qty"/>
</mx:columns>
</mx:DataGrid>
<s:Label width="100%" color="blue"
text="Specify the number of lines and click Fill Grid first. Then you can click Print."/>
<s:TextInput id="dataItems" text="35"/>
<s:HGroup>
<s:Button id="setDP" label="Fill Grid" click="setdgProvider(int(dataItems.text));"/>
<s:Button id="printDG" label="Print" click="doPrint();"/>
</s:HGroup>
</s:VGroup>
</s:Panel>
</s:Application>

"Flexicious" : not able to change the search functionality dynamically in a data Grid

"Flexicious" a third party component library built for handling very larg data set in DataGrid for flex, The issue is, i am not able to change the search functionality dynamically in a data Grid.
<flxs:FlexDataGridColumn id="multiselect" dataField="Name" headerText="Name"
filterControl="NumericTextInput" headerAlign="center">
<flxs:headerRenderer>
<fx:Component>
<controls:ComboBox change="changeSel(event)" width="10" height="41" dataProvider="outerDocument.searchArray}">
<fx:Script>
<![CDATA[
import com.flexicious.controls.ComboBox;
import mx.controls.Alert;
public function changeSel(event:Event):void{
var cbox:ComboBox = event.currentTarget as ComboBox;
if(cbox.selectedItem=="Less Than"){
outerDocument.multiselect.filterOperation="LessThanEquals";
//Alert.show(""+outerDocument.multiselect.filterOperation);
}else if(cbox.selectedItem=="Greator Than"){
outerDocument.multiselect.filterOperation="GreaterThanEquals";
//Alert.show(""+outerDocument.multiselect.filterOperation);
}else if(cbox.selectedItem=="Equal To"){
outerDocument.multiselect.filterOperation="Equals";
//Alert.show(""+outerDocument.multiselect.filterOperation);
}else if(cbox.selectedItem=="Begins With"){
outerDocument.multiselect.filterOperation="BeginsWith";
//Alert.show(""+outerDocument.multiselect.filterOperation);
}
}
]]>
</fx:Script>
</controls:ComboBox>
</fx:Component>
</flxs:headerRenderer>
</flxs:FlexDataGridColumn>
Now when i select any option from the rendered combobox i am not able to change filteroption, however when i alter the filteroperation it dose show me the changed operatioin but in functionality it doesn't change.
You should call grid.rebuildFilter() after changing the filterOperation

Check Spark DataGrid cells' contents programmatically?

I'm using the Spark DataGrid for the first time and finding it generally very usable. There's something I'd like to do with the contents of my grid now that I've drawn it though and I'm a bit stuck as how to proceed.
I'd like to make a function that runs through each cell of a certain column in the DataGrid, that checks each value against an Array of predefined values; if it finds a match, it should then highlight the cell as conflicting, by changing its colour.
I know you can access a particular cell's item renderer, by using the getItemRendererAt() function, and passing the column and row indices. But I can't see how I would, for example, loop through the values in each column.
I may well be going about this all wrong, in which case feel free to push me onto the right path. Equally if it's possible to do what I'm trying to do, I'd love to hear how.
Thanks!
Actually, you should create your own <s:GridItemRenderer /> and use it as an itemRenderer of your dataGrid.
This way, you will be able to change the color of the cell depending on the data property of the <s:GridItemRenderer />.
Here is an example of how you could do it:
<?xml version="1.0" encoding="utf-8"?>
<s:GridItemRenderer xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx" >
<fx:Script>
<![CDATA[
private function isValid(value:uint):Boolean
{
//whatever;
return true;
}
]]>
</fx:Script>
<s:BorderContainer width="100%" height="100%">
<s:borderStroke>
<s:SolidColorStroke color="{isValid(data)?#00FF00:#FF0000}" />
</s:borderStroke>
<s:UITextField label="{data}" />
</s:BorderContainer>
</s:GridItemRenderer>
Using the example above, also Override the "set data" to change the color everytime you change the data, and not only on the grid creation
<?xml version="1.0" encoding="utf-8"?>
<s:GridItemRenderer xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx" >
<fx:Script>
<![CDATA[
import mx.controls.ColorPicker;
import mx.events.FlexEvent;
import mx.utils.ColorUtil;
override public function set data(value:Object):void{
super.data = value;
if(data.different == 1){
solidColor.color = 255;
}
}
]]>
</fx:Script>
<s:BorderContainer width="100%" height="100%">
<s:borderStroke>
<s:SolidColorStroke id="solidColor" />
</s:borderStroke>
<s:UITextFieldGridItemRenderer label="{data.name}" />
</s:BorderContainer>
</s:GridItemRenderer>
Then the next steps are easy, clone your dataProvider from the datagrid and then compare both, and if the item is changed, just set "1" to ,for example, the flag "different" in the example above and then the itemRenderer will call itself and change de color automatically

View Navigator Hide Specific Tab Not TabBar

I'm trying to figure out whether it is possible to define view navigators and selectively hide some depending on a particular user state?
For example I have two navigator tabs one which is a sign in tab and the other shows a users policy. I only want the policy tab to be visible if the user has signed in:
<s:ViewNavigator id="policyTab" width="100%" height="100%" firstView="views.policy.PoliciesView">
<s:navigationContent>
<s:Button id="policyTabButton" label="Policies" click="tabButton_clickHandler(event)" />
</s:navigationContent>
</s:ViewNavigator>
Sign in tab is navigator:
<s:ViewNavigator id="signInTab" width="100%" height="100%" firstView="views.SignInView">
<s:navigationContent>
<s:Button id="signInTabButton" icon="#Embed('images/lockSmall.png')" click="tabButton_clickHandler(event)" />
</s:navigationContent>
</s:ViewNavigator>
Everything that I've researched points me to hiding the entire tab bar which I don't want to do. I've tried simply calling signInTab.visible = false; but is doesn't work.
Any help would be appreciated.
It is true that you can't hide the contents of a TabbedViewNavigator, but there is another way to adjust the content to hide tabs. Basically you can remove the tab from the TabbedViewNavigator to hide it and re-add it to show it again. I've come up with a very simple example which seems to do what you are asking.
TabbedViewNavTest.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
applicationDPI="160"
preinitialize="preinitializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import views.Tab2View;
private static var app:TabbedViewNavigatorApplication;
public static function adjustTabBar():void {
if(app.navigators.length > 1) {
removeTab2();
} else {
addTab2();
}
}
private static function removeTab2():void {
app.tabbedNavigator.removeItemAt(1);
}
private static function addTab2():void {
var tab2:ViewNavigator = new ViewNavigator();
tab2.label = "Tab2";
tab2.percentWidth = 100;
tab2.percentHeight = 100;
tab2.firstView = Tab2View;
app.tabbedNavigator.addItemAt(tab2, 1);
}
protected function preinitializeHandler(event:FlexEvent):void {
app = this;
}
]]>
</fx:Script>
<s:ViewNavigator id="tab1" label="Tab1" width="100%" height="100%" firstView="views.Tab1View"/>
<s:ViewNavigator id="tab2" label="Tab2" width="100%" height="100%" firstView="views.Tab2View"/>
</s:TabbedViewNavigatorApplication>
Tab1View.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
title="Tab1">
<fx:Script>
<![CDATA[
protected function showHideButton_clickHandler(event:MouseEvent):void {
TabbedViewNavTest.adjustTabBar();
}
]]>
</fx:Script>
<s:Button id="showHideButton" label="Click Me!" click="showHideButton_clickHandler(event)" />
</s:View>
Tab2View is just an empty view that was created when I created the project.
While this should do what you need it to do, I'm wondering if there is a better way to achieve what you are attempting to do. For instance, in the case you originally presented of a login tab which disappears when the user logs in you could have created your application as a generic application with 2 states: notLoggedIn and loggedIn. In the notLoggedIn state you only have a view show that presents the login screen, or have a tabbedViewNavigator show which has the login and policy tabs. In the logged in state, you have a separate tabbedViewNavigator which has only the policy tab or perhaps the other tabs available when a user is logged in. If you want me to create an example of what I mean, let me know and I can do that.

Make a tab blink in Spark (Flex)

In a Flex 4 app (with Spark components) I have a ViewStack with various screens, and a TabBar to navigate between them. I'd like the screens to be able to "blink" their tab when something happens in them (like Windows task bar buttons).
How can I do this? My idea is to hack the blinking state into the screen's label (inherited from NavigatorContent) by putting a * in it when blinking, and somehow reading that in a custom tab bar skin.
Is there an easier way? If now, how exactly can I implement mine?
This is a bit hard to explain since it isn't the easiest thing to do, but I'll give it my best. I would create a <s:TabBar /> with a dataProvider of an array of all views in your viewstack and create a custom item renderer for your TabBar which then contains a custom component that extends ButtonBarButton that has a blinking property that's 2-way binded and a custom skin to actually show it blinking, like this:
(man that was a mouthful)
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:local="*">
<fx:Script>
<![CDATA[
import mx.collections.ArrayList;
]]>
</fx:Script>
<s:TabBar dataProvider="{new ArrayList([view1,view2])}">
<s:itemRenderer>
<fx:Component>
<local:BlinkingTab label="{data.label}" blink="#{data.isBlinking}" skinClass="BlinkingTabSkin" />
</fx:Component>
</s:itemRenderer>
</s:TabBar>
<mx:ViewStack>
<local:Foo id="view1" label="View 1" />
<local:Foo id="view2" label="View 2" />
</mx:ViewStack>
</s:Application>
In this case, my views extends 'NavigatorContent', however, we need to be able to express a boolean flag to say that the tab needs to blink, like so:
<s:NavigatorContent xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
implements="ITabView">
<fx:Script>
<![CDATA[
private var _blink:Boolean = false;
[Bindable]
public function get isBlinking():Boolean
{
return this._blink;
}
public function set isBlinking(value:Boolean):void
{
this._blink = value;
}
]]>
</fx:Script>
</s:NavigatorContent>
You'll notice that the view is implementing ITabView. That's only there for typesafing the 'isBlinking' property, but it's optional. When you want your tab to blink, you just need to set this to 'true'. But now we need to get the tab to actually blink. In the custom component 'BlinkingTab' we created for the TabBar, we need to take in the blink property and change the skin state appropriately like so:
<s:ButtonBarButton xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
private var _blink:Boolean;
[Bindable]
public function get blink():Boolean
{
return this._blink;
}
public function set blink(value:Boolean):void
{
this._blink = value;
}
override protected function getCurrentSkinState():String
{
if(!selected && enabled && this._blink)
{
return super.getCurrentSkinState()+'Blinking';
}else{
return super.getCurrentSkinState();
}
}
override protected function mouseEventHandler(event:Event):void
{
super.mouseEventHandler(event);
if(event.type == MouseEvent.CLICK)
{
blink = false;
}
}
]]>
</fx:Script>
</s:ButtonBarButton>
You'll notice that the skin state will only have the 'blinking' string on it if it's enabled and not selected. If it is selected, it won't blink; and if the user clicks on the tab, it will remove the blinking flag which should propagate back to the view (I'm not certain about this part, could always override the 'selected' property or something). And the last part is the skin; you need to create a custom skin so that you can add a blinking animation to your tab. Just create a new skin with a ButtonBarButton host component that uses the TabBarButtonSkin and add these new states:
<s:State name="upBlinking" basedOn="up" stateGroups="blinking" />
<s:State name="overBlinking" basedOn="over" stateGroups="blinking" />
<s:State name="downBlinking" basedOn="down" stateGroups="blinking" />
From here, you need to create your own state based blinking. This is not fully tested, but I think I helped you get 95% of the way. Hope this helps.
BTW, this method is 100% legit. No hacking and you can reuse every single part of the code for somewhere else :)