Flex 4: Get the pressed object - apache-flex

My Skin:
<s:DataGroup id="view1" width="100%" height="100%" itemRenderer="views.itemRenderers.BrickItemRenderer" dataProvider="{hostComponent.createArray()}">
<s:layout>
<s:TileLayout />
</s:layout>
</s:DataGroup>
My View for create object 'bricks'
[Bindable]
public function createArray():ArrayCollection
{
var dataBrick:ArrayCollection = new ArrayCollection();
var data:DataAboutBrick;
for (var x:int = 0; x < 5; x++)
for (var y:int = 0; y < 7; y++)
{
data = new DataAboutBrick();
data.x = 0;
data.y = 0;
data.color = colorBrick;
dataBrick.addItem(data);
}
return dataBrick;
}
Class DataAboutBrick for saved data about object:
public class DataAboutBrick extends Object
{
public function DataAboutBrick()
{
super();
}
public var x:int;
public var y:int;
public var color:uint = 0xFF0000;
public var id:String;
}
Mediator:
private function btnBricknew_clickHandler(event:BaseBrickEvent):void
{
view.colorBrick = model.currentColor;
}
Mediator change color all object when clicked on object. And need only change the color of the object to be pressed.

Assuming you have Brick and BrickSkin defined, you can define the functionality to change the color in BrickItemRenderer as below:
<?xml version="1.0"?>
<spark:DefaultComplexItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:spark="spark.skins.spark.*">
<fx:Script><![CDATA[
[Bindable("dataChanged")]
override public function set data(value:Object):void
{
super.data = value;
var brick:Brick = new Brick();
brick.colorBrick = value.color;
brick.addEventListener(MouseEvent.CLICK, brickClicked,false,0,true);
this.addElement(brick);
}
private function brickClicked(event:Event)
{
event.stopImmediatePropagation();
event.preventDefault();
data.color = 0x00FF00;// Please make sure your color variable defined in DataAboutBrick.as is Bindable.
}
]]></fx:Script>
</spark:DefaultComplexItemRenderer>

Related

I want to create a custom check box which toggles between label and image

I want to create a custom reusable component by extending a spark Button class so that it has a checkbox and a label which says Show Image. When checkbox is selected an image will be displayed instead of the label. The Image path should be exposed as an API. How can we extend spark.components.Button to have it check box with labe or image (image path should be dynamic).
I tried to extend Button class as below but not sure how to create check box in it and how to pass image path as parameter to that.
package myClasses
{
import spark.components.Button;
public class ImageCheckBox extends Button
{
public function ImageButton()
{
super();
this.buttonMode = true;
}
}
}
I want to use the custom components something like below in application.
<myClasses:ImageCheckBox skinClass="mySkins.HelpButtonSkin" path="...."" label="Show Image" />
Something like this
package myClasses {
import flash.events.Event;
import spark.components.CheckBox;
import spark.components.Image;
import spark.components.Label;
import spark.components.supportClasses.SkinnableComponent;
public class ImageCheckBox extends SkinnableComponent {
[SkinPart(required=true)]
public var checkBox:CheckBox;
[SkinPart(required=true)]
public var labelComp:Label;
[SkinPart(required=true)]
public var image:Image;
private var pathChanged:Boolean = false;
private var _path:String;
public function get path():String {
return _path;
}
public function set path(value:String):void {
if (_path != value) {
_path = value;
pathChanged = true;
invalidateProperties();
}
}
private var labelChanged:Boolean = false;
private var _label:String;
public function get label():String {
return _label;
}
public function set label(value:String):void {
if (_label != value) {
_label = value;
labelChanged = true;
invalidateProperties();
}
}
public function ImageCheckBox() {
super();
setStyle("skinClass", ImageCheckBoxSkin);
}
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName, instance);
if (instance == checkBox) {
checkBox.addEventListener(Event.CHANGE, checkBoxChangeHandler)
}
else if (instance == labelComp) {
labelComp.text = label;
}
else if (instance == image) {
image.source = path;
}
}
override protected function partRemoved(partName:String, instance:Object):void {
super.partRemoved(partName, instance);
if (instance == checkBox) {
checkBox.removeEventListener(Event.CHANGE, checkBoxChangeHandler)
}
}
override protected function getCurrentSkinState():String {
return checkBox.selected ? "selected" : super.getCurrentSkinState();
}
override protected function commitProperties():void {
if (labelChanged) {
labelChanged = false;
labelComp.text = label;
}
if (pathChanged) {
pathChanged = false;
image.source = path;
}
super.commitProperties();
}
private function checkBoxChangeHandler(event:Event):void {
invalidateSkinState();
}
}}
And skin
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
xmlns:mx="library://ns.adobe.com/flex/mx">
<!-- host component -->
<fx:Metadata>
<![CDATA[
/**
* #copy spark.skins.spark.ApplicationSkin#hostComponent
*/
[HostComponent("myClasses.ImageCheckBox")]
]]>
</fx:Metadata>
<s:states>
<s:State name="normal"/>
<s:State name="selected"/>
</s:states>
<s:HGroup width="100%" height="100%" gap="3">
<s:CheckBox id="checkBox"
verticalCenter="0"
height="100%"/>
<s:Label id="labelComp"
verticalCenter="0" verticalAlign="middle"
width="100%" height="100%"
visible.normal="true" includeInLayout.normal="true"
visible.selected="false" includeInLayout.selected="false"/>
<s:Image id="image"
verticalCenter="0"
width="100%" height="100%"
fillMode="scale" scaleMode="letterbox"
visible.normal="false" includeInLayout.normal="false"
visible.selected="true" includeInLayout.selected="true"/>
</s:HGroup>

Row renderer with height depending on row index

I have an IDropInListItemRenderer that is being used inside a List. The height of the row depends on both the data and it's position in the List's view.
How do I remeasure as soon as the row index changes?
updateDisplayList doesn't get called every time, and also by that point it's too late because the List has already measured it.
edit
The effect I'm trying to achieve is similar to iOS where the header for a section sticks to the top
Here is the basic renderer that doesn't measure correctly:
import mx.controls.Label;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
import mx.events.FlexEvent;
public class MyRowRenderer extends UIComponent implements IListItemRenderer, IDropInListItemRenderer {
private static const HEADER_HEIGHT:int = 20;
private static const LABEL_HEIGHT:int = 20;
private var _data:Object;
private var _label:Label;
private var _header:Label;
private var _listData:BaseListData;
public function MyRowRenderer() {
super();
}
[Bindable("dataChange")]
public function get data():Object {
return _data;
}
public function set data(value:Object):void {
this._data = value;
invalidateProperties();
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}
[Bindable("dataChange")]
public function get listData():BaseListData {
return _listData;
}
public function set listData(value:BaseListData):void {
_listData = value;
}
override protected function createChildren():void {
super.createChildren();
_header = new Label();
addChild(_header);
_label = new Label();
addChild(_label);
}
override protected function measure():void {
super.measure();
if (_label == null || _header == null) {
return;
}
var h:Number = LABEL_HEIGHT;
if (_listData.rowIndex == 0) {
h += HEADER_HEIGHT;
}
explicitHeight = measuredHeight = height = h;
}
override protected function commitProperties():void {
super.commitProperties();
_label.text = _data.label;
_header.text = _data.header;
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
_header.visible = _header.includeInLayout = (_listData.rowIndex == 0);
if (_header.visible) {
_header.move(0, 0);
_header.setActualSize(unscaledWidth, HEADER_HEIGHT);
_label.move(0, HEADER_HEIGHT);
_label.setActualSize(unscaledWidth, LABEL_HEIGHT);
} else {
_label.move(0, 0);
_label.setActualSize(unscaledWidth, LABEL_HEIGHT);
}
}
}
}
I ended up creating a subclass of List and overriding the shiftRow function to dispatch a custom RowIndexChangeEvent. In the row renderer's set listData it adds an event listener to the owner for the RowIndexChangeEvent and invalidates it's properties, size and displaylist.

Linking a webcam in a flex application

i am having a very strange problem while linking a webcam i xperience following error
ArgumentError: Error #2126: NetConnection object must be connected.
at flash.net::NetStream/ctor()
at flash.net::NetStream()
Following is my code in main.mxml
<fx:Script>
<![CDATA[
import flash.media.Camera;
import flash.media.Video;
import flash.net.NetConnection;
import mx.core.UIComponent;
import com.kahaf.plutay.* ;
private var inVideo:Video;
private var outVideo:Video;
private var inVideoWrapper:UIComponent;
private var camera:Camera;
private var mic:Microphone;
private var inStream:NetStream;
private var outStream:NetStream;
private function defaultVideoMode(): void
{
VideoPanel.width = 726;
VideoPanel.height = 494;
inVideo.width = 726;
inVideo.height = 494;
}
private function showInComingVideo():void
{
inVideo = new Video(VideoPanel.width,VideoPanel.height);
inVideo.attachNetStream(inStream);
inVideoWrapper = new UIComponent();
inVideoWrapper.addChild(inVideo);
VideoPanel.addElement(inVideoWrapper);
defaultVideoMode();
}
private function setupVideo(event:MouseEvent): void
{
camera = Camera.getCamera();
mic = Microphone.getMicrophone();
mic.setLoopBack(false);
mic.setUseEchoSuppression(true);
camera.setMode(640,480,20);
camera.setQuality(65536,90);
var conn:NetConnection = Connection.getConnection().conn;
inStream = new NetStream(conn);
inStream.play(conn);
showInComingVideo();
}
]]>
<s:Group x="283" y="330" width="234" height="149" id="VideoPanel" >
</s:Group>
<s:Button x="447" y="151" label="Click Me." click="setupVideo(event)"/>
here is the code of my connection class :
import flash.net.NetConnection;
public class Connection extends NetConnection
{
public static var conObj:Connection;
public var conn:NetConnection;
public var target:Object;
public var selector:Function;
public function Connection()
{
conn = new NetConnection;
target = null;
selector = null;
conn.client = this;
}
public static function getConnection():Connection
{
if(conObj == null)
{
conObj = new Connection();
}
return conObj;
}
}
This the correct order when handling NetConnection and NetStreams:
Create and establish the NetConnection (NetConnection.connect())
Wait for the NetConnection.Connect.Success event (NetStatusEvent.NET_STATUS)
Create your NetStream and attach the connected NetConnection to it
Publish/play your stream

Stop List From Scrolling

I have a datagrid that's using a custom itemrender with a button in it. I have a problem whereby when I click on a button the datagrid list scrolls its self. How can I prevent this behaviour?
Extended datagrid
<mx:DataGrid xmlns:mx="http://www.adobe.com/2006/mxml"
doubleClickEnabled="false"
alternatingItemColors="[#ffffff, #f1f1f1]"
mouseDown="mdhandler(event)"
sortableColumns="true"
xmlns:datagrids="components.content.contents.datagrids.*"
creationComplete="_creationcomplete(event)">
<mx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import components.preview.PreviewPlayEvent;
import mx.controls.Button;
import components.preview.PreviewPlay;
import components.content.contents.FixedHelp.FixedHelp;
import mx.events.FlexEvent;
import mx.core.Application;
import mx.events.ToolTipEvent;
import flash.utils.describeType;
import mx.utils.ObjectUtil;
import components.remix.PadDisplay.PadContent;
import components.remix.PadDisplay.PalletteCode;
import mx.core.IUIComponent;
import mx.controls.Image;
import mx.managers.DragManager;
import mx.core.DragSource;
import mx.events.DragEvent;
// Embed icon image.
[Embed(source='assets/proxy.png')]
public var dragImg:Class;
private var _scrollEnabled:Boolean=true;
private var _currentpath:String="";
public static const TYPE_ARRAY:Array=["loop", "one-shot sample", "stem", "track"]
private function _creationcomplete(e:FlexEvent=null):void
{
addEventListener(Event.ENTER_FRAME, enterframe, false, 0, true);
addEventListener(PreviewPlayEvent.PLAY, previewplayrequest, false, 0, true);
addEventListener(PreviewPlayEvent.STOP,previewstoprequest,false,0,true)
}
private function previewplayrequest(e:PreviewPlayEvent):void
{
_currentpath=e._path;
//Application.application.previewplay(e._path)
invalidateList();
}
private function previewstoprequest(e:PreviewPlayEvent):void
{
_currentpath="";
//Application.application.previewplay(e._path)
invalidateList();
}
public function get critera():String
{
return _currentpath;
}
public function set criteria(value:String):void
{
_currentpath=value;
}
private function enterframe(e:Event):void
{
if (Application.application.hashelp == false)
{
}
else
{
removeEventListener(Event.ENTER_FRAME, enterframe);
var xml:XML=Application.application.helpxml;
var fh:FixedHelp=Application.application.fixedhelp;
var helptext:String=Application.application.helpxml.studio.loops.text;
fh.addItem(helptext, this);
}
}
private function mdhandler(e:MouseEvent):void
{
describeType(e.currentTarget)
e.currentTarget.toString()
if (e.currentTarget.selectedItem != null && getQualifiedClassName(e.target) != "mx.controls::Button")
{
_scrollEnabled=false
var dragdata:XML=XML(e.currentTarget.selectedItem) as XML
var ds:DragSource=new DragSource()
var dragdataasObject:Object=ObjectUtil.copy(e.currentTarget.selectedItem)
ds.addData(dragdataasObject, PadContent.LOOP_FORMAT);
//trace(ds.dataForFormat(PadContent.LOOP_FORMAT)) // I expect xml data to trace out here but it does not
var imageproxy:Image=new Image();
imageproxy.source=dragImg;
imageproxy.height=40;
imageproxy.width=40;
DragManager.doDrag(this, ds, e, imageproxy, (this.x - e.stageX) + 40, (this.y - e.stageY) + 130)
this.selectedItem=null;
}
else
{
e.stopImmediatePropagation();
}
}
private function userLabelFunction(item:Object, column:DataGridColumn):String
{
var newstr:String=new String(item.t + "\n" + TYPE_ARRAY[item.ty])
return newstr;
}
private function catFunction(item:Object, column:DataGridColumn):String
{
var newstr:String=TYPE_ARRAY[item.ty];
return newstr;
}
private function bpmFunction(item:Object, column:DataGridColumn):int
{
var newstr:Number=new Number(item.bp);
return newstr;
}
private function beatCountFunction(item:Object, column:DataGridColumn):int
{
var newstr:int=new int(item.bc);
return newstr;
}
private function sortbpm(obj1:Object, obj2:Object):int
{
var valueA:Number=obj1.bp;
var valueB:Number=obj2.bp;
return ObjectUtil.numericCompare(valueA, valueB);
}
private function sortbeatcount(obj1:Object, obj2:Object):int
{
var valueA:Number=obj1.bc;
var valueB:Number=obj2.bc;
return ObjectUtil.numericCompare(valueA, valueB);
}
public function get scrollEnabled():Boolean
{
return _scrollEnabled;
}
public function set scrollEnabled(value:Boolean):void
{
_scrollEnabled=value;
}
override protected function dragScroll():void
{
if (_scrollEnabled)
{
super.dragScroll();
}
}
]]>
</mx:Script>
<mx:columns>
<mx:DataGridColumn dataField="r"
headerText=""
itemRenderer="components.content.contents.datagrids.ImageRendererLoops"/>
<mx:DataGridColumn dataField="t"
headerText="Title"
labelFunction="userLabelFunction"/>
<mx:DataGridColumn dataField="bc"
headerText="Beats"
labelFunction="beatCountFunction"
sortCompareFunction="sortbeatcount"/>
<mx:DataGridColumn dataField="BPM"
headerText="BPM"
labelFunction="bpmFunction"
sortCompareFunction="sortbpm"/>
<mx:DataGridColumn itemRenderer="components.preview.PreviewPlay"/>
</mx:columns>
</mx:DataGrid>
Item Renderer
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.controls.listClasses.IDropInListItemRenderer">
<mx:Script>
<![CDATA[
import mx.controls.DataGrid;
import components.content.contents.datagrids.LoopMastersDataGrid;
import components.remix.PadDisplay.PadContent;
import mx.controls.listClasses.BaseListData;
[Embed(source='assets/play_20.png')]
[Bindable]
public var play20Img:Class;
public static const PLAYING:String="playing";
public static const LOADING:String="loading";
public static const IDLE:String="idle";
private var _listData:BaseListData;
private var _bpm:int;
private var _path:String;
private var _state:String="idle";
public function get listData():BaseListData
{
return _listData;
}
public function set listData(value:BaseListData):void
{
_listData=value;
var criteria:String = (_listData.owner as LoopMastersDataGrid).critera;
if(this._path==criteria)
{
// this track is playing
previewbutton.styleName="stopPreviewButtonStyle";
}else
{
// this track is not playing
previewbutton.styleName="playPreviewButtonStyle";
}
//trace("list data crit=="+criteria);
}
override public function set data(value:Object):void
{
super.data=value;
this._path=new String(PadContent.LOOP_ROOT + value.r + "/" + value.u + ".rocudo");
this._bpm=value.bp;
//trace(this._path);
}
private function sendPreviewRequest(event:Event):void
{
switch(this._state)
{
case(PreviewPlay.IDLE):
(listData.owner as LoopMastersDataGrid).dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.PLAY,this._bpm,this._path));
break;
case(PreviewPlay.LOADING):
// preview play probably shouldnt care about loading
break;
case(PreviewPlay.PLAYING):
(listData.owner as LoopMastersDataGrid).dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.STOP,this._bpm,this._path));
break;
}
//dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.PLAY,this._bpm,this._path));
}
/** override protected function commitProperties():void
{
super.commitProperties();
this._state=PreviewPlay.IDLE;
}**/
]]>
</mx:Script>
<mx:Button id="previewbutton"
width="20"
height="20" click="sendPreviewRequest(event)" styleName="playPreviewButtonStyle">
</mx:Button>
</mx:HBox>
Update
I removed my mouse down handler from the datagrid and removed the cusom component. Clicking on a item in the datagrid makes the datagrid scroll so that the item selected appears first in the list. This is the behaviour I need to stop.

Some [Bindable] properties in Flex work, some don't

Problem solved, see below
Question
I'm working in Flex Builder 3 and I have two ActionScript 3 classes (ABC and XYZ) and a Flex MXML project (main.mxml). I have an instance of XYZ as a property of ABC, and I want XYZ's properties to be visible ([Bindable]) in the Flex project in text controls.
Unfortunately, only prop3 and prop4 update when they are changed. I've entered the debugger to make sure that prop1 and prop2 change, but they are not being updated in the text controls.
Here's the code:
ABC.as
[Bindable]
public class ABC extends UIComponent {
/* Other properties */
public var xyz:XYZ = new XYZ();
/* Methods that update xyz */
}
XYZ.as
[Bindable]
public class XYZ extends Object {
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
}
/* getters and setters for prop2, prop3, and prop4 */
}
main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="com.*" />
<com:ABC id="abc" />
<mx:Text text="{abc.xyz.prop1}" />
<mx:Text text="{abc.xyz.prop2}" />
<mx:Text text="{abc.xyz.prop3}" />
<mx:Text text="{abc.xyz.prop4}" />
</mx:Application>
Answer
It's not apparent from the small code snippets that I posted, but from within XYZ I was updating _prop3 and _prop4 using their setters. In constrast, I updated _prop1 and _prop2 through their private variables, not their setters. Thus, properties 1 and 2 were not dispatching update events.
It looks like your getters are returning voids. They should be returning uints, according to your field types.
Otherwise your code should be working fine. I've assembled and tested a working version with a Timer that sets all four values, so you can see all four updating:
Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="onCreationComplete()">
<mx:Script>
<![CDATA[
private function onCreationComplete():void
{
var t:Timer = new Timer(1000);
t.addEventListener(TimerEvent.TIMER, t_tick);
t.start();
}
private function t_tick(event:TimerEvent):void
{
var i:uint = Timer(event.currentTarget).currentCount;
abc.xyz.prop1 = i;
abc.xyz.prop2 = i;
abc.xyz.prop3 = i;
abc.xyz.prop4 = i;
}
]]>
</mx:Script>
<local:ABC id="abc" />
<mx:VBox>
<mx:Text text="{abc.xyz.prop1}" />
<mx:Text text="{abc.xyz.prop2}" />
<mx:Text text="{abc.xyz.prop3}" />
<mx:Text text="{abc.xyz.prop4}" />
</mx:VBox>
</mx:Application>
ABC.as
package
{
import mx.core.UIComponent;
[Bindable]
public class ABC extends UIComponent
{
public var xyz:XYZ = new XYZ();
public function ABC()
{
super();
}
}
}
XYZ.as
package
{
[Bindable]
public class XYZ extends Object
{
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
public function XYZ()
{
super();
}
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
}
public function get prop2():uint {
return _prop2;
}
public function set prop2(value:uint):void {
_prop2 = value;
}
public function get prop3():uint {
return _prop3;
}
public function set prop3(value:uint):void {
_prop3 = value;
}
public function get prop4():uint {
return _prop4;
}
public function set prop4(value:uint):void {
_prop4 = value;
}
}
}
Have a look at those, plug things in and you should see it all come together. Post back if you have any questions. Cheers.
When you define your bindable sources through the use of getters and setters, the bindings don't seem to work. The solution is to declare a bindable event for your getter and dispatch the event in your setter:
[Bindable]
public class XYZ extends Object {
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
[Bindable(event="prop1Changed")]
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
dispatchEvent (new Event ("prop1Changed"));
}
/* getters and setters for prop2, prop3, and prop4 */
}
So whenever your private member changes, an event is dispatched that notifies any component linked to the getter that the property has changed.

Resources