Friday, September 12, 2008

Getting Click Events from the Slider Track in Flex

In the past few days I've run into two separate situations in which I needed to be able to get an event when the track of a slider was clicked. In one case, I was using an HSlider control to set the volume of a music player. When the track was clicked the thumb of the slider would nicely tween to its new position, but the volume of the sound would abruptly jump when the thumb was done moving.

Ideally you would be able to tween the volume at the same rate that the slider thumb is moving, but to do this you need to be able to know when the track is clicked, before the slider thumb is done moving. Furthermore, you need to know the values the slider is moving from and to.

Ordinarily, the only event the slider component will dispatch when the track is clicked is the "change" event, and this happens after the slider thumb is done moving to the new location on the track. It is possible, however, to receive the track click event by extending the HSlider or VSlider classes. Below is some example code. Though we shouldn't really be accessing mx_internal members, I can't see any other way to do it. I'm open to suggestions as to another way to get access to this event, and the from and to values of the slider.


package {
import flash.events.MouseEvent;
import mx.controls.HSlider;
import mx.core.mx_internal;

use namespace mx_internal;

public class ExtendedHSlider extends HSlider {
override protected function createChildren():void {
super.createChildren();

super.mx_internal::getTrackHitArea().addEventListener(MouseEvent.MOUSE_DOWN,
function(event:MouseEvent):void {
var fromValue:Number = value;
var toValue:Number = mx_internal::getValueFromX(event.localX);
trace("Hooray! We're getting events when the track is clicked!");
trace("The slider is going to move from " + fromValue + " to " + toValue);
});
}
}
}

2 comments:

gsb said...

Thank You.
This fits nicely into a spot I was having trouble with.

gsb

Anonymous said...

THANK YOU!!!!
looking for hours how to access the trackHitArea

super.mx_internal::getTrackHitArea()