How to show PopUp with in the screen area In Flex and AS3 - apache-flex

Hi i am trying to show my popup on the image mouse over
it is showing fine
when i trying mouse over right side last images popup is going out of the screen
Here TalentInfoPopUp is **TitleWindow
This is my sample code
private static var staticWindow :TalentInfoPopUp = null;
private static var visibleWindow:TalentInfoPopUp = null;
public static function show(t:Object, parent : DisplayObject, x:Number , y:Number):void
{
if(staticWindow == null)
{
visibleWindow = staticWindow = PopUpManager.createPopUp( parent , TalentInfoPopUp , false) as TalentInfoPopUp;
}
else if(visibleWindow == null)
{
visibleWindow = staticWindow;
PopUpManager.addPopUp(staticWindow, parent, false);
}
PopUpManager.centerPopUp(staticWindow);
staticWindow.talent = t;
staticWindow.x = x;
staticWindow.y =y;
PopUpManager.bringToFront(staticWindow);
staticWindow.talent = t;
staticWindow.move(x,y);
staticWindow.callLater(staticWindow.setPosition,[x,y]);
//staticWindow.setPosition(x,y);
}
private function setPosition(nx:int,ny:int):void
{
var maxWidth:int = stage.width ;
var maxHeight:int = stage.height;
if(nx>maxWidth-width)
{
nx=nx-width;
}
if(ny>maxHeight-height)
{
ny=ny-height;
}
this.move(nx,ny);
}

Try using systemManager.screen.width and systemManager.screen.height instead of stage.width and stage.height; also learn about the localToGlobal and globalToLocal methods and how to use them.

Related

Coners of Custom Frame are getting trimmed in Xamarin forms iOS

I have created a custom renderer for a frame to have rounded corners only on 2 sides. The code works fine in Android but in iOS the rounded corners are getting trimmed if the background color of frame is white and border color is blue like below image.
Custom Renderer IOS
public class CustomFrameRenderer : FrameRenderer
{
public override void LayoutSubviews()
{
base.LayoutSubviews();
UpdateCornerRadius();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(CustomFrame.CornerRadius) ||
e.PropertyName == nameof(CustomFrame))
{
UpdateCornerRadius();
}
}
// A very basic way of retrieving same one value for all of the corners
private double RetrieveCommonCornerRadius(CornerRadius cornerRadius)
{
var commonCornerRadius = cornerRadius.TopLeft;
if (commonCornerRadius <= 0)
{
commonCornerRadius = cornerRadius.TopRight;
if (commonCornerRadius <= 0)
{
commonCornerRadius = cornerRadius.BottomLeft;
if (commonCornerRadius <= 0)
{
commonCornerRadius = cornerRadius.BottomRight;
}
}
}
return commonCornerRadius;
}
private UIRectCorner RetrieveRoundedCorners(CornerRadius cornerRadius)
{
var roundedCorners = default(UIRectCorner);
if (cornerRadius.TopLeft > 0)
{
roundedCorners |= UIRectCorner.TopLeft;
}
if (cornerRadius.TopRight > 0)
{
roundedCorners |= UIRectCorner.TopRight;
}
if (cornerRadius.BottomLeft > 0)
{
roundedCorners |= UIRectCorner.BottomLeft;
}
if (cornerRadius.BottomRight > 0)
{
roundedCorners |= UIRectCorner.BottomRight;
}
return roundedCorners;
}
private void UpdateCornerRadius()
{
var cornerRadius = (Element as CustomFrame)?.CornerRadius;
if (!cornerRadius.HasValue)
{
return;
}
var roundedCornerRadius = RetrieveCommonCornerRadius(cornerRadius.Value);
if (roundedCornerRadius <= 0)
{
return;
}
var roundedCorners = RetrieveRoundedCorners(cornerRadius.Value);
var path = UIBezierPath.FromRoundedRect(Bounds, roundedCorners, new CGSize(roundedCornerRadius, roundedCornerRadius));
var mask = new CAShapeLayer { Path = path.CGPath };
NativeView.Layer.Mask = mask;
//NativeView.Layer.CornerRadius = 0;
NativeView.ClipsToBounds = true;
NativeView.Layer.MaskedCorners = (CoreAnimation.CACornerMask)3;
}
}
Can someone please help me to resolve below issue.
Thanks.
You could check the following code
private void UpdateCornerRadius()
{
var cornerRadius = (Element as Frame)?.CornerRadius;
if (!cornerRadius.HasValue)
{
return;
}
var roundedCornerRadius = RetrieveCommonCornerRadius(cornerRadius.Value);
if (roundedCornerRadius <= 0)
{
return;
}
var roundedCorners = RetrieveRoundedCorners(cornerRadius.Value);
NativeView.Layer.MasksToBounds = true;
var path = UIBezierPath.FromRoundedRect(Bounds, roundedCorners, new CGSize(roundedCornerRadius, roundedCornerRadius));
var mask = new CAShapeLayer { Path = path.CGPath };
mask.Frame = Bounds;
mask.LineWidth = 1;
mask.StrokeColor = UIColor.SystemBlueColor.CGColor; // border color
mask.FillColor = UIColor.Clear.CGColor; // bg color , you need to set it as clear otherwise it will cover its child element
mask.ShadowRadius = 0;
NativeView.Layer.AddSublayer(mask);
// NativeView.Layer.MaskedCorners = (CoreAnimation.CACornerMask)3;
}
A mask takes a layer, and trim that visual to match the mask.
So if a layer is a rectangle with black borders, and your mask is an oval,
an oval will appear with the color of the rectangle that it masks.
But it will not round those rectangle borders, just cut them out.
What you need to do instead is to build a layer that will replace NativeView.Layer
With your rounded rectangle, without using the mask.
Or change those values on the elements in the layer that already exist, directly.

Xamarin Forms - Resize Camera Picture

Someone helped me get this code for taking a picture using xamarin forms labs camera:
picker = DependencyService.Get<IMediaPicker> ();
task = picker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 800,
});
img.BackgroundColor = Color.Gray;
Device.StartTimer (TimeSpan.FromMilliseconds (250), () => {
if (task != null) {
if (task.Status == TaskStatus.RanToCompletion) {
Device.BeginInvokeOnMainThread (async () => {
//img.Source = ImageSource.FromStream (() => task.Result.Source);
var fileAccess = Resolver.Resolve<IFileAccess> ();
string imageName = "img_user_" + User.CurrentUser().id + "_" + DateTime.Now.ToString ("yy_MM_dd_HH_mm_ss") + ".jpg";
fileName = imageName;
fileAccess.WriteStream (imageName, task.Result.Source);
fileLocation = fileAccess.FullPath(imageName);
FileStream fileStream = new FileStream(fileAccess.FullPath(imageName), FileMode.Open, System.IO.FileAccess.Read);
imageUrl = (string)test[0]["url"];
img.Source = imageUrl;
});
}
return task.Status != TaskStatus.Canceled
&& task.Status != TaskStatus.Faulted
&& task.Status != TaskStatus.RanToCompletion;
}
return true;
});
It saves the image, but the actual size of the phone picture taken is huge, is there a way to resize it.
UPDATE: The original answer is not useful, see below for updated answer. The issue was the PCL library was very slow and consumed too much memory.
ORIGINAL ANSWER (do not use):
I found an image I/O library, ImageTools-PCL, which I forked on github and trimmed down what wouldn't compile in Xamarin, keeping the modifications to minimum and the result seems to work.
To use it download the linked repository, compile it with Xamarin and add the DLLs from Build folder to your Forms project.
To resize an image you can do this (should fit the context of your question)
var decoder = new ImageTools.IO.Jpeg.JpegDecoder ();
ImageTools.ExtendedImage inImage = new ImageTools.ExtendedImage ();
decoder.Decode (inImage, task.Result.Source);
var outImage = ImageTools.ExtendedImage.Resize (inImage, 1024, new ImageTools.Filtering.BilinearResizer ());
var encoder = new ImageTools.IO.Jpeg.JpegEncoder ();
encoder.Encode (outImage, fileAccess.CreateStream (imageName));
ImageSource imgSource = ImageSource.FromFile (fileAccess.FullPath (imageName));
UPDATED ANSWER:
Get Xamarin.XLabs from nuget, learn about using Resolver, create an IImageService interface with Resize method.
Implementation for iOS:
public class ImageServiceIOS: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (File.Exists(sourceFile) && !File.Exists(targetFile))
{
using (UIImage sourceImage = UIImage.FromFile(sourceFile))
{
var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
if (!Directory.Exists(Path.GetDirectoryName(targetFile)))
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
UIGraphics.BeginImageContextWithOptions(new CGSize((float)width, (float)height), true, 1.0f);
// UIGraphics.GetCurrentContext().RotateCTM(90 / Math.PI);
sourceImage.Draw(new CGRect(0, 0, (float)width, (float)height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
if (targetFile.ToLower().EndsWith("png"))
resultImage.AsPNG().Save(targetFile, true);
else
resultImage.AsJPEG().Save(targetFile, true);
}
}
}
}
}
Implementation of the service for Android:
public class ImageServiceDroid: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (!File.Exists(targetFile) && File.Exists(sourceFile))
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options()
{
InJustDecodeBounds = false,
InPurgeable = true,
};
using (var image = BitmapFactory.DecodeFile(sourceFile, options))
{
if (image != null)
{
var sourceSize = new Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
string targetDir = System.IO.Path.GetDirectoryName(targetFile);
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = (int)(maxResizeFactor * sourceSize.Width);
var height = (int)(maxResizeFactor * sourceSize.Height);
using (var bitmapScaled = Bitmap.CreateScaledBitmap(image, height, width, true))
{
using (Stream outStream = File.Create(targetFile))
{
if (targetFile.ToLower().EndsWith("png"))
bitmapScaled.Compress(Bitmap.CompressFormat.Png, 100, outStream);
else
bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 95, outStream);
}
bitmapScaled.Recycle();
}
}
image.Recycle();
}
else
Log.E("Image scaling failed: " + sourceFile);
}
}
}
}
#Sten's answer might encounter out-of-memory problem on some android devices. Here's my solution to implement the ResizeImage function
, which is according to google's "Loading Large Bitmaps Efficiently" document:
public void ResizeImage (string sourceFile, string targetFile, int reqWidth, int reqHeight)
{
if (!File.Exists (targetFile) && File.Exists (sourceFile)) {
var downImg = decodeSampledBitmapFromFile (sourceFile, reqWidth, reqHeight);
using (var outStream = File.Create (targetFile)) {
if (targetFile.ToLower ().EndsWith ("png"))
downImg.Compress (Bitmap.CompressFormat.Png, 100, outStream);
else
downImg.Compress (Bitmap.CompressFormat.Jpeg, 95, outStream);
}
downImg.Recycle();
}
}
public static Bitmap decodeSampledBitmapFromFile (string path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options ();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile (path, options);
// Calculate inSampleSize
options.InSampleSize = calculateInSampleSize (options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeFile (path, options);
}
public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
You can do this natively for each platform and use an interface. Heres an example for IOS
In your PCL project you need to add an interface
public interface IImageResizer
{
byte[] ResizeImage (byte[] imageData, double width, double height);
}
Then to resize an image in your code, you can load the IOS implementation of that interface using the DependencyService and run the ResizeImage method
var resizer = DependencyService.Get<IImageResizer>();
var resizedBytes = resizer.ResizeImage (originalImageByteArray, 400, 400);
Stream stream = new MemoryStream(resizedBytes);
image.Source = ImageSource.FromStream(stream);
IOS Implementation, add this class to your IOS project.
[assembly: Xamarin.Forms.Dependency (typeof (ImageResizer_iOS))]
namespace YourNamespace
{
public class ImageResizer_iOS : IImageResizer
{
public byte[] ResizeImage (byte[] imageData, double maxWidth, double maxHeight)
{
UIImage originalImage = ImageFromByteArray (imageData);
double width = 300, height = 300;
double maxAspect = (double)maxWidth / (double)maxHeight;
double aspect = (double)originalImage.Size.Width/(double)originalImage.Size.Height;
if (maxAspect > aspect && originalImage.Size.Width > maxWidth) {
//Width is the bigger dimension relative to max bounds
width = maxWidth;
height = maxWidth / aspect;
}else if (maxAspect <= aspect && originalImage.Size.Height > maxHeight){
//Height is the bigger dimension
height = maxHeight;
width = maxHeight * aspect;
}
return originalImage.Scale(new SizeF((float)width,(float)height)).AsJPEG ().ToArray ();
}
public static MonoTouch.UIKit.UIImage ImageFromByteArray(byte[] data)
{
if (data == null) {
return null;
}
MonoTouch.UIKit.UIImage image;
try {
image = new MonoTouch.UIKit.UIImage(MonoTouch.Foundation.NSData.FromArray(data));
} catch (Exception e) {
Console.WriteLine ("Image load failed: " + e.Message);
return null;
}
return image;
}
}
}
An update from the Xamarin Media Plugin allows you to resize the image
https://github.com/jamesmontemagno/MediaPlugin
... barring that, and you need a more generic resize option (say the image comes from a web call, and not the device, then have a look at:
https://github.com/InquisitorJax/Wibci.Xamarin.Images

How do you set different columns to have alternatingItemColors on DataGridColumns?

On a DataGrid, setting alternatingItemColors will apply the color scheme to all of the columns of that grid. I'm looking for a way to define different alternating colors for each column. Is there a baked in way to do this?
Have a look on this:http://blog.flexexamples.com/2008/09/24/setting-background-colors-on-a-datagrid-column-in-flex/
I hope this would be helpful for you ;)
public class BlocksTable extends DataGrid
{
public static const VALID_COLOR:uint = 0xDBAB21;
public static const INVALID_COLOR:uint = 0xC7403E;
public function BlocksTable()
{
super();
}
override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number, color:uint, dataIndex:int):void
{
var contentHolder:ListBaseContentHolder = ListBaseContentHolder(s.parent);
var background:Shape;
if (rowIndex < s.numChildren)
{
background = Shape(s.getChildAt(rowIndex));
}
else
{
background = new FlexShape();
background.name = "background";
s.addChild(background);
}
background.y = y;
// Height is usually as tall is the items in the row, but not if
// it would extend below the bottom of listContent
var height:Number = Math.min(height,
contentHolder.height -
y);
var g:Graphics = background.graphics;
g.clear();
var fillColor:uint;
if(dataIndex < this.dataProvider.length)
{
if(this.dataProvider.getItemAt(dataIndex).IS_VALID)
{
fillColor = VALID_COLOR;
}
else
{
fillColor = INVALID_COLOR;
}
}
else
{
fillColor = color;
}
g.beginFill(fillColor, getStyle("backgroundAlpha"));
g.drawRect(0, 0, contentHolder.width, height);
g.endFill();
}
}

as3: reloading an image

I have an image that I am attempting to load, and then reload. Here is my code for the loading of the image:
public function loadImage(url:String, _w:int, _h:int):void
{
this._stwidth = _w;
this._stheight = _h;
this._imageURL = url;
if(!_imageURL)
{
return;
}
this.alpha = 1.0; //need this because we might have just faded the image out
_ldr.alpha = 0.0;
_prog.alpha = 1.0;
_sqr.alpha = 0.0;
_sqr.graphics.clear();
if(_hasLoaded)
{
try
{
_ldr.close();
_ldr.unload();
}
catch(e:Error)
{
//trace("bmdisplay has loaded once, but there was an error: " + e.message);
}
}
_ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(Event.INIT, onOpen);
_ldr.load(new URLRequest(_imageURL));
}
For some reason, this code will not load the image without issuing an Error upon the 2nd load.
Can someone please help me figure this out?
I am totally lost on why my variable _asLoaded would do me wrong.
I have an onComplete() handler, which sets that var to true, and I never set it to false after that.
I don't know what else I should be trying...
Thanks
Sometimes back I wrote a helper class to achieve something similar. The helper class extends Loader and provides automatic scaling of image. Here is the code for that class:package {
import flash.display.Loader;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
public class ImageLoader extends Loader {
private var _imageURL:String; // URL of image
private var _imageBoundary:Rectangle; // boundary rectangle for the image
private var _loaded:Boolean; // flag which tells whether image is loaded or not.
private var _isLoading:Boolean; // flag which say if any loading is in progress
//Constructor function, which calls Loader's constructor
// and loads and resize the image
public function ImageLoader(url:String = null, rect:Rectangle = null):void {
super();
_imageURL = url;
_imageBoundary = rect;
_loaded = false;
_isLoading = false;
loadImage();
}
// sets the image for the loader and loads it
public function set imageURL(url:String):void {
_imageURL = url;
loadImage();
}
// sets the boundary of the image and resizes it
public function set boundary(rect:Rectangle):void {
_imageBoundary = rect;
resizeImage();
}
private function removeListeners():void {
this.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
this.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
this.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onComplete(e:Event):void {
_loaded = true;
_isLoading = false;
removeListeners();
resizeImage();
}
//In case of error, we are not propogating the event
private function onError(e:Event):void {
e.stopImmediatePropagation();
removeListeners();
}
// real loading goes here
// it first closes and unloads the loader and
// then loads the image
private function loadImage():void {
if (_isLoading) {
trace("Some loading is in progess");
return;
}
try {
this.close();
this.unload();
}
catch(e:Error) {
//discarded
}
if (!_imageURL)
return;
_loaded = false;
_isLoading = true;
this.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
this.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
this.load(new URLRequest(_imageURL));
}
// standard resizing function for image so that it's
// aspect ratio is maintained.
private function resizeImage():void {
if (!_imageBoundary || !_loaded)
return;
var aspect:Number = width / height;
var cAspect:Number = _imageBoundary.width / _imageBoundary.height;
if (aspect <= cAspect) {
this.height = _imageBoundary.height;
this.width = aspect * this.height;
}
else {
this.width = _imageBoundary.width;
this.height = this.width / aspect;
}
this.x = (_imageBoundary.width-this.width)/2 + _imageBoundary.x;
this.y = (_imageBoundary.height-this.height)/2 + _imageBoundary.y;
}
}
} And you can use it like this:var _imageLoader:ImageLoader = new ImageLoader();
_imageLoader.imageURL = "http://some-image-url";
_imageLoader.boundary = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); // or whatever suits you
ImageLoader extends Loader class so you can listen to all the Events dispatches by Loader class. Hope it helps.
i would declare _ldr inside the function so its dead every time you start this function. and i also would not use this unload() and close() methods. its much simpler if make some thing like this (you need to have a empty movieclip called "ldrHelper"):
public function loadImage(url:String, _w:int, _h:int):void
{
// do your job and die bravely, no need to be global
var _ldr:Loader = new Loader();
this._stwidth = _w;
this._stheight = _h;
this._imageURL = url;
if(!_imageURL)
{
return;
}
this.alpha = 1.0; //need this because we might have just faded the image out
// now you will need to make alpha = 1 on ldrHolder since _ldr is dead after this function
ldrHolder.alpha = 0.0;
_prog.alpha = 1.0;
_sqr.alpha = 0.0;
_sqr.graphics.clear();
// remove the old image, doesn't matter whether its empty or not
while(ldrHolder.numChildren > 0){
ldrHolder.removeChildAt(0);
}
//add image
ldrHolder.addChild(_ldr);
_ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(Event.INIT, onOpen);
_ldr.load(new URLRequest(_imageURL));
}
Try instantiating new Loader, probably trying to recycle it is giving you the problem

Flex: Updating a Tree control

I've a tree control with checkboxes that uses the control from http://www.sephiroth.it/file_detail.php?id=151#
Somehow I can't get the control to update when I change the dataProvider (i.e. by clicking a checkbox) the only way I can get it to update is to use the scrollbar. How do I force the update? I've tried all possible methods I can figure out? (see update below)
Also how can I reset the Tree (collpasing all nodes, scroll to the top in a large tree)?
package offerta.monkeywrench.components
{
import offerta.monkeywrench.components.componentClasses.TreeCheckBoxItemRenderer;
import mx.collections.ArrayCollection;
import mx.events.TreeEvent;
public class WatchTree extends TreeCheckBox
{
public var idProperty:String;
public var watchFactory:Function;
private var _wSet:Boolean = false;
/* clientId: */
private var _clientId:String;
[Bindable]
public function get clientId():String
{
return _clientId;
}
public function set clientId(value:String):void
{
this._clientId = value;
}
/* //clientId */
/* watching: */
private var _watching:ArrayCollection;
[Bindable]
public function set watching(value:ArrayCollection):void
{
this._watching = value;
}
public function get watching():ArrayCollection
{
return this._watching;
}
/* //watching */
override public function initialize() :void
{
super.initialize();
addEventListener("itemCheck", onItemCheck, false, 0, true);
}
private function isWatching(id:String):Boolean
{
for each(var w:Object in this._watching)
{
if(w[this.idProperty]==id) return true;
}
return false;
}
private function onItemCheck(event:TreeEvent):void
{
var item:Object = event.item as Object;
var currentValue:uint = (event.itemRenderer as TreeCheckBoxItemRenderer).checkBox.checkState;
if(item.children==null)
{
currentValue==2 ? addWatch(item.Id) : removeWatch(item.Id);
}
else
{
for each(var x:Object in item.children)
{
currentValue==2 ? addWatch(x.Id) : removeWatch(x.Id);
}
}
updateParents(item, currentValue);
updateChilds(item, currentValue);
this.dataProvider.refresh();
super.invalidateProperties();
super.invalidateDisplayList();
super.updateDisplayList(this.unscaledWidth, this.unscaledHeight);
}
private function updateParents(item:Object, value:uint):void
{
var checkValue:String = (value == ( 1 << 1 | 2 << 1 ) ? "2" : value == ( 1 << 1 ) ? "1" : "0");
var parentNode:Object = item.parent;
if(parentNode)
{
for each(var x:Object in parentNode.children)
{
if(x.checked != checkValue)
{
checkValue = "2"
}
}
parentNode.checked = checkValue;
updateParents(parentNode, value);
}
}
private function updateChilds(item:Object, value:uint):void
{
var middle:Boolean = (value&2<<1)==(2<<1);
if(item.children!=null && item.children.length>0&&!middle)
{
for each(var x:Object in item.children)
{
x.checked = value == (1<<1|2<<1) ? "2" : value==(1<<1) ? "1" : "0";
updateChilds(x, value);
}
}
}
private function addWatch(id:String):void
{
if(isWatching(id)) return;
this._watching.addItem(this.watchFactory(id, this.clientId));
}
private function removeWatch(id:String):void
{
for(var i:int=0, n:int=this._watching.length; i<n; ++i)
{
if(this._watching[i][this.idProperty]==id)
{
this._watching.removeItemAt(i);
return;
}
}
}
public function update(__watching:ArrayCollection, __clientId:String):void
{
clientId = __clientId;
watching = __watching;
if(this.dataProvider!=null)
{
var ws:ArrayCollection = ArrayCollection(this.dataProvider);
for each(var group:Object in ws)
{
var count:int = 0;
for each(var child:Object in group.children)
{
if(isWatching(child.Id))
{
child.checked = "1";
count++;
}
}
group.checked = (count==0 ? "0" : (count==group.children.length ? "1" : "2"));
}
this._wSet = false;
var dp:ArrayCollection = ArrayCollection(this.dataProvider);
dp.refresh();
super.invalidateProperties();
super.invalidateDisplayList();
super.updateDisplayList(this.unscaledWidth, this.unscaledHeight);
//scroll up the list???
//collapse? (doesn't work)
this.expandItem(null, false);
}
}
}
}
I've found the Tree control a little touchy in Flex. The way I ended up forcing a redraw was to disconnect the dataProvider and reconnect it, then force validation, something a bit like this :
private function forceRedraw(tree:Tree, dataProvider:Object):void
{
var scrollPosition:Number = tree.verticalScrollPosition;
var openItems:Object = tree.openItems;
tree.dataProvider = dataProvider;
tree.openItems = openItems;
tree.validateNow();
tree.verticalScrollPosition = scrollPosition;
}
I guess this incidentally answers the second part of your question since all you'd have to do is null out the openItems collection and set the verticalScrollPosition to 0.
You might have another problem: whenever you check an item the tree scrolls to the top and this is just annoying. To solve this problem you should update the TreeCheckBox.as file this way:
in function checkHandler:
private function checkHandler( event: TreeEvent ): void;
comment the commitProperties(); call.
Now it should work well.
Cheers.
I've had some minor problem with this solution, var scrollPosition:Number = tree.verticalScrollPosition; is constantly 0??

Resources