Here is a functional example:
<?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;
public function go():void{
Alert.show("The focus will return to txtOne. Look: ");
}
]]>
</mx:Script>
<mx:VBox>
<mx:TextInput id="txtOne" text="1" focusOut="go()"/>
<mx:TextInput id="txtTwo" text="2"/>
</mx:VBox>
</mx:Application>
When you change from txtOne to txtTwo, the Alert is showed and after pressing OK, the focus will return to txtOne. I don't want that to happen. How to solve this?
Alert.show has close callback argument, so you will know, when it is closed and set focus to something else. Update: you should have flag, indicating, that focus out event can be processed:
private var needAlert:Boolean = true;
public function go():void
{
if (needAlert)
{
Alert.show("The focus will return to txtOne. Look: ",
"", 0, null, myCloseHandler);
needAlert = false;
}
}
private function myCloseHandler(event:CloseEvent):void
{
this.setFocus();
needAlert = true;
}
Try this also to ensure the focus goes where the user wanted it too
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.IFocusManagerComponent;
private var ignoreFocusChange:Boolean = false;
private var focusTargetOnReturn: IFocusManagerComponent;
public function go():void
{
if(!ignoreFocusChange){
focusTargetOnReturn = focusManager.getFocus();
Alert.show("The focus will not return to txtOne anymore. Look: ",
"", 0, null, myCloseHandler);
}
}
private function myCloseHandler(event:CloseEvent):void
{
ignoreFocusChange = true;
focusManager.setFocus(focusTargetOnReturn);
ignoreFocusChange = false;
}
]]>
</fx:Script>
<mx:VBox>
<mx:TextInput id="txtOne" text="1" focusOut="go()"/>
<mx:TextInput id="txtTwo" text="2"/>
</mx:VBox>
Related
I just started working with Flex. I know it's pathetic but it's a long story.
Now, the problem I am facing is that I have a list component which has a dataprovider on it. What I would like to do is when an item on the list is clicked I would like to have a check sign right next to the label.
Below is the component:
<s:List id="tabList" width="100%"
borderVisible="false" click="tabList_clickHandler(event)"
selectedIndex="{this.hostComponent.selectedIndex}"
itemRenderer="MultiTabListRenderer" />
Below is the Itemrenderer code:
protected function AddCheck_clickHandler(event:MouseEvent):void {
// TODO Auto-generated method stub
var checkLabel:Label;
checkLabel = new Label();
checkLabel.text = "checkMark";
var e: ItemClickEvent = new ItemClickEvent(ItemClickEvent.ITEM_CLICK, true);
e.item = data;
e.index = itemIndex;
dispatchEvent(e);
this.checkRectGroup.addElementAt(checkLabel, e.index);
}
<s:Label id="customMultitabList" text="{data.label}"
left="10" right="0" top="6" bottom="6" click="AddCheck_clickHandler(event)"/>
My code inside the function is wrong which is mainly due to the fact that I do not understand each and everything in flex. I am not in a mood to learn the language in detail because it's not a long term work for me. Also, in the renderer file when I use s:List instead of s:label I do not see the labels anymore. Of course I replace the attribute text with dataprovider={data.selectedItem}.
One way to approach this is to add a field to the objects in your dataProvider that tracks whether or not the item has been selected.
Then, in your item renderer, you inspect this field and decide whether or not to display the checkmark. Here's a working example app and renderer:
Application:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:local="*"
creationComplete="application1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
import mx.events.FlexEvent;
import mx.events.PropertyChangeEvent;
import mx.events.PropertyChangeEventKind;
private var collection:ArrayCollection;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
collection = new ArrayCollection([
{ label: 1, selected: false },
{ label: 2, selected: false },
{ label: 3, selected: false }]);
listbert.dataProvider=collection;
}
protected function listbert_clickHandler(event:MouseEvent):void
{
var index:int = listbert.selectedIndex;
var item:Object = listbert.selectedItem;
item.selected = !item.selected;
// Create these events because the items in the ArrayCollection
// are generic objects. It shouldn't be necessary if items in
// your collection are a Class that extends EventDispatcher
// see ArrayList::startTrackUpdates()
var e:PropertyChangeEvent = new PropertyChangeEvent(
PropertyChangeEvent.PROPERTY_CHANGE, false,false,
PropertyChangeEventKind.UPDATE, 'selected', !item.selected,
item.selected, item);
collection.dispatchEvent(new CollectionEvent(
CollectionEvent.COLLECTION_CHANGE, false,false,
CollectionEventKind.UPDATE, index, index, [e]));
}
]]>
</fx:Script>
<s:List id="listbert" click="listbert_clickHandler(event)" itemRenderer="TestRenderer"/>
</s:Application>
Item Renderer:
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" >
<fx:Script>
<![CDATA[
override public function set data(value:Object):void
{
super.data = value;
labelDisplay.text = value.label;
if (value.selected)
checkMarkLabel.text = "✓";
else
checkMarkLabel.text = "";
}
]]>
</fx:Script>
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<s:Label id="labelDisplay" />
<s:Label id="checkMarkLabel" />
</s:ItemRenderer>
I have a Flex application which sends a query to a database when an user clicks a button. Since the query might be heavy, and can take up to a minute, I want to display an alert, which will close only after an event comes back from the database (user won't be able to close it himself). Is it possible in Flex? How do I do that?
I have functions sendQuery() and dataEventHandler(). I think I need to put code in sendQuery() to display the alert and in dataEventHandler() to close it after data comes from the DB, but how do I make the alert "unclosable" by the user?
The built in Flex Alert class will always have some type of close button.
However, there is no reason you can't create your own component; and then open and close it using the PopUpManager.
Following code may help you… (One of the solution...)
You can find I have made Solution 1 and Solution 2… You can use any one of it and third solution is to create your own Custom Component.
Please find below code…. You can use below logic to solve your problem..
Use Timer to check if data received or you can dispatch custom event and call updateAlertPosition function.
Hope it may help: -
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
private var minuteTimer:Timer;
private var alert:Alert;
private var displayInitialText:String = "Data Not Received, Please wait....";
private var displayDataReveivedText:String = "Data Received...";
private function timerInit():void
{
//Logic to check if data Received.
minuteTimer = new Timer(3000);
minuteTimer.addEventListener(TimerEvent.TIMER, updateAlertPosition);
minuteTimer.start();
}
private function updateAlertPosition(event:Event = null):void {
minuteTimer.stop();
//Solution 1
//add your flag here if y you want to check if data is received or not
//if(Data Received)
alert.mx_internal::alertForm.mx_internal::buttons[0].enabled = true;
alert.mx_internal::alertForm.mx_internal::buttons[1].enabled = true;
alert.mx_internal::alertForm.mx_internal::textField.text = displayDataReveivedText;
//Solution 2
//alert.enabled = true;
//If you want to remove it automatically
//closeAutomatically();
}
private function closeAutomatically():void
{
PopUpManager.removePopUp(alert);
}
private function clickHandler():void
{
//Start Timer
timerInit();
//Solution 1
alert = Alert.show(displayInitialText, "Alert", Alert.OK|Alert.CANCEL,this,alertCloseHandler);
alert.mx_internal::alertForm.mx_internal::buttons[0].enabled = false;
alert.mx_internal::alertForm.mx_internal::buttons[1].enabled = false;
//Solution 2
//alert.enabled = false;
}
private function alertCloseHandler(event:CloseEvent):void
{
if(event.detail == Alert.CANCEL)
{
//Some Code on close
}
else
{
//Some Code on OK
}
}
]]>
</fx:Script>
<s:Button label="Show Alert" x="100" y="100" click="clickHandler()"/>
</s:Application>
make a 0-0.2 alpha shape what covers the whole application (probably you'll want to listen for resizeevents), and add a custom panel to the middle of it, with the message.
As an idea you can create a custom alert then:
Show Alert
Disable Application.
Hide Alert.
Enable Application.
An alert example:
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
creationComplete="onCreationComplete(event)">
<s:Rect>
<s:fill>
<s:SolidColor color="0xFFFFFF"/>
</s:fill>
<s:stroke>
<s:SolidColorStroke />
</s:stroke>
</s:Rect>
<s:Label text="Please Wait..."/>
<fx:Script>
<![CDATA[
import mx.core.FlexGlobals;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
public static function show():void
{
PopUpManager.createPopUp(FlexGlobals.topLevelApplication);
}
public static function hide():void
{
PopUpManager.removePopUp(this);
FlexGlobals.topLevelApplication.enabled = true;
}
protected function onCreationComplete(event:FlexEvent):void
{
PopUpManager.centerPopUp(this);
FlexGlobals.topLevelApplication.enabled = false;
}
]]>
</fx:Script>
</s:Group>
Usage:
YourAlert.show();
YourAlert.hide();
#Alex, I used your code but modify it a bit, because there was some errors:
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="creationCompleteHandler()" width="100%" height="100%">
<fx:Script>
<![CDATA[
import mx.core.FlexGlobals;
import mx.core.UIComponent;
import mx.managers.PopUpManager;
///////////////////////////////////////
//// public functions - my group is ImageViewer.mxml component
public static function show():ImageViewer {
return PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, ImageViewer) as ImageViewer;
}
public function hide():void {
PopUpManager.removePopUp(this);
FlexGlobals.topLevelApplication.enabled = true;
}
////////////////////////////
//// component events
private function creationCompleteHandler():void {
PopUpManager.centerPopUp(this);
FlexGlobals.topLevelApplication.enabled = false;
}
]]>
</fx:Script>
</s:Group>
And call it like:
var imageviewer:ImageViewer = ImageViewer.show();
//imageviewer.imageURL = _value_dto.value;
I'm facing a strange issue with flex and validator.
Here is the code:
TestMain.xml
<?xml version="1.0" encoding="utf-8"?>
<s:Application 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.Alert;
import mx.validators.StringValidator;
import utils.ValidableProperty;
[Bindable] public var nameID:ValidableProperty;
public function start():void {
var nameIDValidator:StringValidator = new StringValidator();
nameIDValidator.required = true;
nameIDValidator.maxLength = 35;
nameID = new ValidableProperty(nameIDValidator);
nameID.validate();
}
]]>
</fx:Script>
<s:applicationComplete>
start();
</s:applicationComplete>
<s:minHeight>600</s:minHeight>
<s:minWidth>955</s:minWidth>
<mx:Form color="0x323232" paddingTop="0">
<s:Label text="See strange behavior of errorString during validator operation with validate."/>
<mx:FormItem label="Name">
<mx:TextInput id="nameInput" width="300" errorString="#{nameID.errorMessage}" text="#{nameID.value}"/>
</mx:FormItem>
</mx:Form>
ValidableProperty.as
package utils
{
import flash.events.EventDispatcher;
import mx.events.PropertyChangeEvent;
import mx.events.ValidationResultEvent;
import mx.validators.Validator;
public class ValidableProperty extends EventDispatcher
{
[Bindable]
public var value:Object;
private var validator:Validator;
[Bindable]
public var isValid:Boolean;
[Bindable]
public var errorMessage:String;
private var statusChangeHandler:Function;
public function ValidableProperty(validator:Validator, statusChangeHandler:Function=null,
target:IEventDispatcher=null) {
super(target);
this.validator = validator;
this.statusChangeHandler = statusChangeHandler;
this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHandler);
}
private function propertyChangeHandler(evt:PropertyChangeEvent):void {
if (evt.property == "value") {
this.validate();
}
}
public function validate():void {
var result:ValidationResultEvent = this.validator.validate(this.value);
this.isValid = (result.type == ValidationResultEvent.VALID);
if (isValid) {
this.errorMessage = null;
}
else {
this.errorMessage = result.message;
}
if (statusChangeHandler != null)
statusChangeHandler();
}
public function set required(required:Boolean):void {
if (validator == null)
return;
validator.required = required;
}
}
}
When you execute this simple code, when writing a value, for example "A", the errorMessage value "this field is required" will disappear but the red color on the inputtext border will still be there with the blue color.
When deleting the A value, this time the blue color will be there with the red one (cannot reproduce all the time) and the error message "this field is required".
What am I missing here? Is it a bug in flex? We cannot have both of red and blue colors on the textinput border.
I am using Eclipse with Flex SDK 4.5.0 (build 20967)
This is not a bug in Flex. This is a bug with how you're coding it all. If you were to follow the example in the documentation, it would work.
<?xml version="1.0" encoding="utf-8"?>
<!-- Simple example to demonstrate StringValidator. -->
<s:Application 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:Declarations>
<mx:StringValidator source="{nameInput}" property="text"
tooShortError="This string is shorter than the minimum length of 4. "
tooLongError="This string is longer than the maximum allowed length of 35."
minLength="4" maxLength="35"/>
</fx:Declarations>
<s:Form>
<s:FormItem label="Name">
<s:TextInput id="nameInput" width="300" text="{nameID.value}"/>
</s:FormItem>
</s:Form>
</s:Application>
I finally resolve this. I was using mx:TextInput instead of s:TextInput. Thanks J_A_X for your suggestion !
Can any one indicata me a small piece of code for making this progress bar move on mic activitylevel. i.e, When spoken on the microphone the progressbar should indicate it.Also which works on internet explorer
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
width="300"
height="100"
creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.net.NetStream;
private var myMic:Microphone;
private var recordingState:String = "idle";
private function init():void {
myMic = Microphone.getMicrophone();
myMic.setSilenceLevel(0);
myMic.rate = 44;
myMic.gain = 100;
micLevel.visible = true;
Security.showSettings(SecurityPanel.MICROPHONE);
myMic.setLoopBack(true);
if (myMic != null)
{
myMic.setUseEchoSuppression(true);
micLevel.setProgress(myMic.activityLevel, 100);
addEventListener(Event.ENTER_FRAME, showMicLevel);
//micLevel.setProgress(myMic.activityLevel, 100);
}
}
]]>
</mx:Script>
<mx:ProgressBar x="0" y="36" mode="manual" id="micLevel" label="" labelPlacement="bottom" width="100" fontSize="10" fontWeight="normal"/>
</mx:Application>
You need to add a callback function for the event. You have it defined as showMicLevel but you have no implementation of that function.
private function showMicLevel(e: Event):void{
micLevel.setProgress(myMic.activityLevel, 100);
}
I want to set the enabled property on a button based on the return value of a function that has one or more parameters. How can I do this?
private function isUserAllowed (userName:Boolean):Boolean {
if (userName == 'Tom')
return true;
if (userName == 'Bill')
return false;
}
<mx:Button label="Create PO" id="createPOButton"
enabled="<I want to call isUserAllowed ('Bill') or isUserAllowed ('Tom') here>"
click="createPOButton_Click()" />
According to the Flex docs, as long as the property is bindable, you can simply do this (I've included the two extra buttons to demonstrate):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
[Bindable]
private var currentUser:String = "Bill";
private function isUserAllowed(user:String):Boolean
{
if (user == "Bill")
{
return true;
}
return false;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="My Button" enabled="{isUserAllowed(currentUser)}" />
<mx:HBox>
<mx:Button label="Try Tom" click="{currentUser = 'Tom'}" />
<mx:Button label="Try Bill" click="{currentUser = 'Bill'}" />
</mx:HBox>
</mx:VBox>
</mx:Application>
Without currentUser marked [Bindable], though, it won't work.
Another way to go, if you wanted to bind more literally to the function (this is also expressed in the docs), would be to have the function respond to an event you dispatch when the current user changes, like so:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()">
<mx:Script>
<![CDATA[
private var _currentUser:String = "Bill";
public function set currentUser(value:String):void
{
if (_currentUser != value)
{
_currentUser = value;
dispatchEvent(new Event("userChanged"));
}
}
[Bindable(event="userChanged")]
private function isUserEnabled():Boolean
{
if (_currentUser == "Bill")
{
return true;
}
return false;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="My Button" enabled="{isUserEnabled()}" />
<mx:HBox>
<mx:Button label="Try Tom" click="{currentUser = 'Tom'}" />
<mx:Button label="Try Bill" click="{currentUser = 'Bill'}" />
</mx:HBox>
</mx:VBox>
</mx:Application>
So there are a couple of ways. IMO, the second seems somehow more proper, but there's definitely nothing wrong with the first. Good luck!
<mx:Button
enabled = "{this.myFunction(this.myVariable)}"
>
or inline:
<mx:Button
enabled = "{(function(arg:Object):Boolean{ ... })(this.myVariable)}"
>
Here's what I've done a few times in similar circumstances:
<mx:Script>
<![CDATA[
[Bindable] var _username : String;
private function isUserAllowed (userName:Boolean):Boolean {
if (userName == 'Tom')
return true;
if (userName == 'Bill')
return false;
}
]]>
</mx:Script>
<mx:Button label="Create PO"
id="createPOButton"
enabled="{isUserAllowed(_username)}"
click="createPOButton_Click()" />
This way, when the Bindable _username changes, it will fire a change notification. Since the label is listening to _username changes (even if it is simply a parameter to another function), the enabled property will be re-evaluated.
<mx:Script>
<![CDATA[
[Bindable]
private var userName : String = "Tom"; // or whatever ...
[Bindable]
private var userAllowed : Boolean;
private function isUserAllowed ():Boolean {
if (userName == 'Tom')
return false;
if (userName == 'Bill')
return false;
return false;
}
]]>
</mx:Script>
<mx:Button label="Create PO" id="createPOButton" enabled="{userAllowed}" addedToStage="isUserAllowed()"/>