Customize the alert box with two buttons - apache-flex

I need to customize my alert box with two button and both the button need to have different skins on them.
I was able to do it for one skin. But i am unable to figure out about the two skins.
My code that i have right now is below:
public function Messages():void
{
Alert.buttonWidth = 100;
Alert.yesLabel = "Accept";
Alert.noLabel = "Reject";
var alert:Alert = Alert.show("Accept video chat request from "+far_alias+"?", "Incoming Video Chat Request", Alert.YES | Alert.NO | Alert.NONMODAL, Sprite(Application.application), handleIncomingCallResponse, null, Alert.YES);
alert.data = cm;
alert.name = alert_name;
alert.styleName = "requestVideoAlert"
_alertDic[alert_name] = alert;
Alert.yesLabel = "Yes";
Alert.noLabel = "No";
}
And the Css code is below:
<mx:Style>
.requestVideoAlert
{
background-color: #000000;
back-color: #000000;
area-fill:#000000;
border-color:#000000;
dropShadowEnabled: false;
button-style-name: cancelbtn;
}
.cancelbtn
{
skin: Embed(source='assets/images/videoChat-cancel-button.png');
}
This give the same skin on both the buttons "Accept" and "Reject"
Can some one help me with this.
Thank you
Zee

I dont know if you already found an solution but if no and you use flex 3 I can help you.
This code should do what you need.
Changing buttons and even changing style for text on buttons.
'
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
initStyles();
var myAlert:Alert = Alert.show("description", "title", Alert.YES | Alert.NO);
var arrOfButtons:Array = myAlert.mx_internal::alertForm.mx_internal::buttons;
var button1:Button = arrOfButtons[0];
var button2:Button = arrOfButtons[1];
// buttons filters
button1.styleName = 'buttonStyle1';
button2.styleName = 'buttonStyle2';
button1.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void
{
// you can change text on buttons as well
var btn:Button = event.target as Button;
var text:UITextField = btn.getChildAt(0) as UITextField;
text.filters = [ new GlowFilter(0x3946C0, 1, 4, 2, 8)];
}
/**
* set style of remove button for alert
**/
private function initButton1Style():void
{
var buttonStyle1:CSSStyleDeclaration = new CSSStyleDeclaration('buttonStyle1');
buttonStyle1.setStyle('fontWeight', "normal");
buttonStyle1.setStyle('fontColor', 0x000000);
buttonStyle1.setStyle('color', 0x000000);
buttonStyle1.setStyle("fillColors", [ 0xffffff, 0xF5A2A2, 0xF5A2A2, 0xffffff ]);
buttonStyle1.setStyle('fontSize', 10);
buttonStyle1.setStyle('themeColor', 0xff0000);
StyleManager.setStyleDeclaration(".buttonStyle1", buttonStyle1, true);
}
/**
* set style of buy button for alert
**/
private function initButton2Style():void
{
var buttonStyle2:CSSStyleDeclaration = new CSSStyleDeclaration('buttonStyle2');
buttonStyle2.setStyle('fontWeight', "normal");
buttonStyle2.setStyle('fontColor', 0x000000);
buttonStyle2.setStyle('color', 0x000000);
buttonStyle2.setStyle("fillColors", [ 0xffffff, 0xBAFFAB, 0xBAFFAB, 0xffffff ]);
buttonStyle2.setStyle('fontSize', 10);
buttonStyle2.setStyle('themeColor', 0x7CCB6C);
StyleManager.setStyleDeclaration(".buttonStyle2", buttonStyle2, true);
}
private function initStyles():void
{
initButton1Style();
initButton2Style();
}
]]>
</mx:Script>
'

Unfortunately, I don't think there's a simple way of doing this - the button styles are set in AlertForm by looping through all the buttons on the Alert and setting their stylename to buttonStyleName. In order to set seperate button styles, I think you'd have to extend both Alert (to use a custom AlertForm class) and AlertForm (to override styleChanged to assign seperate style names).

Try this:
package utils
{
import flash.events.EventDispatcher;
import mx.controls.Alert;
import mx.controls.Button;
import mx.core.mx_internal;
public class AlertUtility extends EventDispatcher
{
use namespace mx_internal;
public static function getYesNoAlert(title:String, message:String,closeFunction:Function):void{
var myAlert:Alert = Alert.show(message, title, Alert.YES | Alert.NO,null,closeFunction,null,Alert.NO);
var arrOfButtons:Array = myAlert.mx_internal::alertForm.mx_internal::buttons;
var button1:Button = arrOfButtons[0];
var button2:Button = arrOfButtons[1];
button1.styleName = 'alertBtnStyle1';
button2.styleName = 'alertBtnStyle2';
}
}
}
and in your style css:
mx|Button.alertBtnStyle1 {
skin: ClassReference("skins.myEmphasizedSkin");
/* desired style */
}
mx|Button.alertBtnStyle2 {
emphasizedSkin: ClassReference("skins.myButtonDefaultSkin");
/* desired style */
}

Related

How to disable the icon on a Flex3 Button

I have a button which I use for sending a message. When the message text is empty, it should not be possible to click the button.
This is all fine and not an issue. The only thing that is bugging me is the fact that I can disable the send button but the image does not get disabled (like I would expect).
Is there a way to do this elegantly because I don't want to provide a sendicon_disabled.png and change it myself (I don't think this should be my job).
You can use the following button for that:
package
{
import mx.controls.Button;
import mx.core.mx_internal;
use namespace mx_internal;
public class IconButton extends Button
{
private var enabledChanged:Boolean = false;
override public function set enabled(value:Boolean):void
{
if (super.enabled == value)
{
return;
}
super.enabled = value;
enabledChanged = true;
invalidateDisplayList();
}
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if (enabledChanged)
{
if (!enabled && currentIcon)
{
currentIcon.alpha = 0.5;
}
enabledChanged = false;
}
}
}
}
You can use your custom alpha value or move it to separate style.

changin the default width and height of the dropdownlist

i want a dropdownlist that is wide enough to accommodate the larger item in the dropdown in display area of the main control.(.i.e. dropdownlist with the functionality of MX Combobox)
please guide me on this .
This will adjust the width of the drop down to the width of the data.
I forget where the example is where i got the code from. The height can be set by rowCount I believe.
package valueObjects.comboBox{
import flash.events.Event;
import mx.controls.ComboBox;
import mx.core.ClassFactory;
import mx.core.IFactory;
import mx.events.FlexEvent;
public class ExtendedComboBox extends ComboBox{
private var _ddFactory:IFactory = new ClassFactory(ExtendedList);
public function ExtendedComboBox(){
super();
}
override public function get dropdownFactory():IFactory{
return _ddFactory;
}
override public function set dropdownFactory(factory:IFactory):void{
_ddFactory = factory;
}
public function adjustDropDownWidth(event:Event=null):void{
this.removeEventListener(FlexEvent.VALUE_COMMIT,adjustDropDownWidth);
if (this.dropdown == null){
callLater(adjustDropDownWidth);
}else{
var ddWidth:int = this.dropdown.measureWidthOfItems(-1,this.dataProvider.length);
if (this.dropdown.maxVerticalScrollPosition > 0){
ddWidth += ExtendedList(dropdown).getScrollbarWidth();
}
this.dropdownWidth = Math.max(ddWidth,this.width);
}
}
override protected function collectionChangeHandler(event:Event):void{
super.collectionChangeHandler(event);
this.addEventListener(FlexEvent.VALUE_COMMIT,adjustDropDownWidth);
}
}
}
package valueObjects.comboBox{
import mx.controls.List;
public class ExtendedList extends List{
public function ExtendedList(){
super();
}
public function getScrollbarWidth():int{
var scrollbarWidth:int = 0;
if (this.verticalScrollBar != null){
scrollbarWidth = this.verticalScrollBar.width;
}
return scrollbarWidth;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" mlns:comboBox="valueObjects.comboBox.*" >
<comboBox:ExtendedComboBox labelField="data.totext()" itemRenderer="mx.controls.Label" />
</mx:Canvas>
You should create custom DropDownList (extending original) and override dataProvider setter and measure() method. In dataProvider setter you should invoke invalidateSize() and in measure you should iterate your data provider and find the largest label (you can assign new text to the label and compare their width).
To increase the height of a combo box's drop-down list, use "rowCount" property. This is for Flex 3.6.0
Check out this example from Flex Examples. You just have to create a skin for the DropDownList and set the popUpWidthMatchesAnchorWidth="false" property.
it is achieved by following code :
public override function set dataProvider(value:IList):void
{
var length:Number = 0;
var array:Array = value.toArray();
super.dataProvider = value;
var labelName:String = this.labelField;
var typicalObject:Object =new Object();
for each(var obj:Object in array)
{
var temp:Number = obj[labelName] .length;
if( length < temp )
{
length = temp;
Alert.show(" length "+length.toString());
typicalObject = obj;
}
//length = length < Number(obj[labelName].length) ? Number(obj[labelName].length) : length
//Alert.show(obj[labelName].length);
this.typicalItem = typicalObject;
}
}
Sorry, better take off both the width and height from the field.

Changing font size in Flex app

How can i change font size in all flex application?
Write a style like
<mx:Style>
global {
fontSize: 20;
}
</mx:Style>
in your main application. It should be inherited by application contents.
Here is a solution to change the font size at runtime.
You can create a Factory class which will take care of text formatting, so you'll have a single place where to change the font size.
public class OtherClass
{
public function OtherClass()
{
var textfield:TextField = new TextField();
textfield = Factory.formatText(textfield );
textfield.text = "Hello World";
addChild(textfield );
}
}
public class Factory
{
public static function formatText(tf:TextField ):TextField
{
var fontName:String = "YourFont";
var fontSize:int = 12;
var fontColor:uint = 0x000000;
var format:TextFormat = new TextFormat( fontName, fontSize , fontColor );
tf.defaultTextFormat = format;
//etc...
return tf;
}
}
You can , of course , pass other parameters to the function in order to retain some flexibility in your text formatting.

Datagrid selects the wrong custom cell in my datagrid

I am working on a problem since a week soon, but I still couldn't make it work as expected. I have a DataGrid which has HBox with a CheckBox an a Label as itemRenderer (see Code below). When I tap in to the Cell the standard itemEditor pops up and lets you enter the content of the label. Thats the standard behavior. I works fine except for 2 problems:
If I enter to much text, the horizontal srollbar pops up, and the cell is filled with that scrollbar. As you see I tried to set the horizontalScrollPolicy to off, but that doesnt work at all... I tried to do that for all the different elements, but the failure is still existent.
When I have filled more than one row, there is an other mistake happening. If I tap on a row, the datagrid selects the one below that row. That's only if one line is already selected. If I tap outside the datagrid and then, tap at any row the itemEditor of the right row will show up... Is there anything now wright in the setup of my set data method?
__
package components
{
import mx.containers.HBox;
import mx.controls.CheckBox;
import mx.controls.Label;
public class ChoiceRenderer extends HBox
{
private var correctAnswer:CheckBox;
private var choiceLabel:Label;
public function ChoiceRenderer()
{
super();
paint();
}
private function paint():void{
percentHeight = 100;
percentWidth = 100;
setStyle("horizontalScrollPolicy", "off");
super.setStyle("horizontalScrollPolicy", "off");
correctAnswer = new CheckBox;
correctAnswer.setStyle("horizontalScrollPolicy", "off");
addChild(correctAnswer);
choiceLabel = new Label;
choiceLabel.setStyle("horizontalScrollPolicy", "off");
addChild(choiceLabel);
}
override public function set data(xmldata:Object):void{
if(xmldata.name() == "BackSide"){
var xmlText:Object = xmldata.TextElements.TextElement.(#position == position)[0];
super.data = xmlText;
choiceLabel.text = xmlText.toString();
correctAnswer.selected = xmlText.#correct_answer;
}
}
}
Thanks in advance!
Markus
I am not sure if this is the reason behind your issues, but the standard way of creating children is to override the createChildren method.
Also, you are missing an else statement - you are not calling super.data when if condition fails. That doesn't look good either.
Try:
package components
{
public class ChoiceRenderer extends HBox {
private var correctAnswer:CheckBox;
private var choiceLabel:Label;
public function ChoiceRenderer() {
super();
percentHeight = 100;
percentWidth = 100;
setStyle("horizontalScrollPolicy", "off");
}
override protected function createChildren():void {
super.createChildren();
correctAnswer = new CheckBox();
addChild(correctAnswer);
choiceLabel = new Label();
choiceLabel.setStyle("horizontalScrollPolicy", "off");
addChild(choiceLabel);
}
override public function set data(xmldata:Object):void {
if(xmldata.name() == "BackSide") {
var xmlText:Object = xmldata.TextElements.TextElement.(#position == position)[0];
super.data = xmlText;
choiceLabel.text = xmlText.toString();
correctAnswer.selected = xmlText.#correct_answer;
}
else {
//what if xmldata.name() is not "BackSide"?
//you are not calling super.data in that case
}
}
}
in order to avoid scroll bar you have to let datagrid have variable height
<mx:DataGrid id="dg"
dataProvider="{dp}"
variableRowHeight="true"
creationComplete="dg.height=dg.measureHeightOfItems(0,dp.length)+dg.headerHeight+2"/>

Flex custom item renderer for the displayed item in the combobox

I am using a custom item renderer in a combobox to display a custom drawing instead of the default text label.
This works fine for the dropdown list but the displayed item ( when the list is closed) is still the textual representation of my object.
Is there a way to have the displayed item rendered the same way as the one in the dropdown?
By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.
package
{
import mx.controls.ComboBox;
import mx.core.UIComponent;
public class ComboBox2 extends ComboBox
{
public function ComboBox2()
{
super();
}
protected var textInputReplacement:UIComponent;
override protected function createChildren():void {
super.createChildren();
if ( !textInputReplacement ) {
if ( itemRenderer != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer to use in place of the text input
textInputReplacement = itemRenderer.newInstance();
addChild(textInputReplacement);
}
}
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
if ( textInputReplacement ) {
textInputReplacement.width = unscaledWidth;
textInputReplacement.height = unscaledHeight;
}
}
}
}
I tried the above solution, but found that the selectedItem did not display when the combobox was closed. A extra line of code was required to bind the itemRenderer data property to the selectedItem:
if ( !textInputReplacement ) {
if ( itemRenderer != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer to use in place of the text input
textInputReplacement = itemRenderer.newInstance();
// ADD THIS BINDING:
// Bind the data of the textInputReplacement to the selected item
BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);
addChild(textInputReplacement);
}
}
I've extended Dane's code a bit further. In some cases clicking did not open the drop box with my renderer and I noticed that the normal Flex ComboBox skins did not fire. Thus in replaceTextInput() I added some additional event listeners and save a reference to the ComboBox button used to display the skins. Now it behaves just like the normal ComboBox.
Here's the code:
package
{
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import mx.binding.utils.BindingUtils;
import mx.controls.Button;
import mx.controls.ComboBox;
import mx.core.IFactory;
import mx.core.UIComponent;
import mx.events.DropdownEvent;
/**
* Extension of the standard ComboBox that will use the assigned 'itemRenderer'
* for both the list items and the selected item.
*
* Based on code from:
* http://stackoverflow.com/questions/269773/flex-custom-item-renderer-for-the-displayed-item-in-the-combobox
*/
public class ComboBoxFullRenderer extends ComboBox
{
protected var textInputReplacement:UIComponent;
private var _increaseW:Number = 0;
private var _increaseH:Number = 0;
/**
* Keeps track of the current open/close state of the drop down list.
*/
protected var _isOpen:Boolean = false;
/**
* Stores a reference to the 'Button' which overlays the ComboBox. Allows
* us to pass events to it so skins are properly triggered.
*/
protected var _buttonRef:Button = null;
/**
* Constructor.
*/
public function ComboBoxFullRenderer() {
super();
}
/**
* Sets a value to increase the width of our ComboBox to adjust sizing.
*
* #param val Number of pixels to increase the width of the ComboBox.
*/
public function set increaseW(val:Number):void {
_increaseW = val;
}
/**
* Sets a value to increase the height of our ComboBox to adjust sizing.
*
* #param val Number of pixels to increase the height of the ComboBox.
*/
public function set increaseH(val:Number):void {
_increaseH = val;
}
/**
* Override the 'itemRenderer' setter so we can also replace the selected
* item renderer.
*
* #param value The renderer to be used to display the drop down list items
* and the selected item.
*/
override public function set itemRenderer(value:IFactory):void {
super.itemRenderer = value;
replaceTextInput();
}
/**
* Override base 'createChildren()' routine to call our 'replaceTextInput()'
* method to replace the standard selected item renderer.
*
* #see #replaceTextInput();
*/
override protected function createChildren():void {
super.createChildren();
replaceTextInput();
}
/**
* Routine to replace the ComboBox 'textInput' child with our own child
* that will render the selected data element. Will create an instance of
* the 'itemRenderer' set for this ComboBox.
*/
protected function replaceTextInput():void {
if ( !textInputReplacement ) {
if ( this.itemRenderer != null && textInput != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer instance to use in place of the text input
textInputReplacement = this.itemRenderer.newInstance();
// Listen for clicks so we can open/close the drop down when
// renderer components are clicked.
textInputReplacement.addEventListener(MouseEvent.CLICK, _onClick);
// Listen to the mouse events on our renderer so we can feed them to
// the ComboBox overlay button. This will make sure the button skins
// are activated. See ComboBox::commitProperties() code.
textInputReplacement.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseEvent);
textInputReplacement.addEventListener(MouseEvent.MOUSE_UP, _onMouseEvent);
textInputReplacement.addEventListener(MouseEvent.ROLL_OVER, _onMouseEvent);
textInputReplacement.addEventListener(MouseEvent.ROLL_OUT, _onMouseEvent);
textInputReplacement.addEventListener(KeyboardEvent.KEY_DOWN, _onMouseEvent);
// Bind the data of the textInputReplacement to the selected item
BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);
// Add our renderer as a child.
addChild(textInputReplacement);
// Listen for open close so we can maintain state. The
// 'isShowingDropdown' property is mx_internal so we don't
// have access to it.
this.addEventListener(DropdownEvent.OPEN, _onOpen);
this.addEventListener(DropdownEvent.CLOSE, _onClose);
// Save a reference to the mx_internal button for the combo box.
// We will need this so we can call its dispatchEvent() method.
for (var i:int = 0; i < this.numChildren; i++) {
var temp:Object = this.getChildAt(i);
if (temp is Button) {
_buttonRef = temp as Button;
break;
}
}
}
}
}
/**
* Detect open events on the drop down list to keep track of the current
* drop down state so we can react properly to a click on our selected
* item renderer.
*
* #param event The DropdownEvent.OPEN event for the combo box.
*/
protected function _onOpen(event:DropdownEvent) : void {
_isOpen = true;
}
/**
* Detect close events on the drop down list to keep track of the current
* drop down state so we can react properly to a click on our selected
* item renderer.
*
* #param event The DropdownEvent.CLOSE event for the combo box.
*/
protected function _onClose(event:DropdownEvent) : void {
_isOpen = false;
}
/**
* When we detect a click on our renderer open or close the drop down list
* based on whether the drop down is currently open/closed.
*
* #param event The CLICK event from our selected item renderer.
*/
protected function _onClick(event:MouseEvent) : void {
if (_isOpen) {
this.close(event);
} else {
this.open();
}
}
/**
* React to certain mouse/keyboard events on our selected item renderer and
* pass the events to the ComboBox 'button' so that the skins are properly
* applied.
*
* #param event A mouse or keyboard event to send to the ComboBox button.
*
*/
protected function _onMouseEvent(event:Event) : void {
if (_buttonRef != null) {
_buttonRef.dispatchEvent(event);
}
}
} // end class
} // end package
Thank you maclema and Maurits de Boer. I added a couple more things to this class to make it fit my needs:
I overrode set itemRenderer so that this will work if you set the itemRenderer through AS instead of mxml. I moved the text input replacement code to its own function to avoid duplication.
I added setters for 'increaseW' and 'increaseH' to resize the combobox if necessary because my renderer was too big for the combobox at first.
I subtracted 25 from the textInputReplacement width so it doesn't ever overlap the dropdown button... may be better to use something more proportional to accommodate different skins and such.
Code:
package
{
import mx.binding.utils.BindingUtils;
import mx.controls.ComboBox;
import mx.core.IFactory;
import mx.core.UIComponent;
public class ComboBox2 extends ComboBox
{
public function ComboBox2()
{
super();
}
protected var textInputReplacement:UIComponent;
private var _increaseW:Number = 0;
private var _increaseH:Number = 0;
public function set increaseW(val:Number):void
{
_increaseW = val;
}
public function set increaseH(val:Number):void
{
_increaseH = val;
}
override public function set itemRenderer(value:IFactory):void
{
super.itemRenderer = value;
replaceTextInput();
}
override protected function createChildren():void
{
super.createChildren();
replaceTextInput();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
unscaledWidth += _increaseW;
unscaledHeight += _increaseH;
super.updateDisplayList(unscaledWidth, unscaledHeight);
if ( textInputReplacement ) {
textInputReplacement.width = unscaledWidth - 25;
textInputReplacement.height = unscaledHeight;
}
}
protected function replaceTextInput():void
{
if ( !textInputReplacement ) {
if ( this.itemRenderer != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer to use in place of the text input
textInputReplacement = this.itemRenderer.newInstance();
addChild(textInputReplacement);
// ADD THIS BINDING:
// Bind the data of the textInputReplacement to the selected item
BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);
addChild(textInputReplacement);
}
}
}
}
}
I was looking for a way to do this using the Spark ComboBox.
This thread was very useful to me but so far there have only been answers on how to do it using an mx:ComboBox. I thought that I should append my answer on how to do it using a spark ComboBox.
Create a new skin of the ComboBox
Hide and disable the textInput
Insert your own component
This is what the skin would look like:
<s:SparkSkin>
<... Lots of other stuff/>
<s:BorderContainer height="25">
<WHATEVER YOU NEED HERE!/>
</s:BorderContainer>
<!-- Disable the textInput and hide it -->
<s:TextInput id="textInput"
left="0" right="18" top="0" bottom="0"
skinClass="spark.skins.spark.ComboBoxTextInputSkin"
visible="false" enabled="false"/>
</s:SparkSkin>
With the Spark ComboBox this process is very easy and does not require you to extend ComboBox.
I found an easier way of changing the renderer for the selected element. This one only works if your element inherits from the TextInput class, in Flex 4.0 or above.
In Flex v4.5, in ComboBase.createChildren at line 1177, you will find that the class definable for the textInput can be passed using the style key textInputClass:
// Mechanism to use MXFTETextInput.
var textInputClass:Class = getStyle("textInputClass");
if (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)
{
textInput = new TextInput();
}
else
{
textInput = new textInputClass();
}
Just change the value of this key in the constructor of your combo and now you have your own renderer for the selectedItem.
public function ComboAvailableProfessor()
{
super();
itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );
setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );
}
Finally you must bind the data property to the selectedItem property in your combo in order to get data displayed.
override protected function createChildren():void
{
super.createChildren();
BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );
}

Resources