We had a situation requiring up and down buttons, and we wanted them to scroll a list. The catch is how to animate the scrolling. Here’s how we did it.
In a nutshell, the Tween class (mx.effects.Tween) allows you to pass 2 numbers and get periodic updates of numbers incrimenting between the them.  For example, given the number 0 and the number 100, we can set the Tween function to increment between them over a period of 10,000ms (10 seconds).  The tween class will then poll a function called “onTweenUpdate” with numbers from 0 to 100 over the 10 second period.

Generally you can write this:

import mx.effects.Tween; 

var myListener:Object = new Object(); 

myListener.onTweenUpdate = function(i:Number) {
// do something with i
} 

var myTween:Tween = new Tween(myListener,0,100,10000);

We then applied this to the scrolling <mx:List> object so that the up button and down button initiate Tween functions to set the scroll position of the list.

Get the source: ScrollTween.mxml

<mx:Script>
<![CDATA[
	import mx.effects.Tween; 

	[Bindable]
	private var myData:Array = [
		'apple',
		'banana',
		'coconut',
		'dragonfruit',
		'elderberry',
		'fig',
		'grape',
		'kiwi',
		'lime',
		'mango',
		'nectarine',
		'orange',
		'pear',
		'raspberry',
		'strawberry',
		'tomato',
		'watermelon'
	]; 

	public function onTweenUpdate(position:Number):void {
		myList.verticalScrollPosition = Math.round(position);
	} 

	public function onTweenEnd(position:Number):void {
		refreshButtons(position);
	} 

	private function refreshButtons(position:Number=0):void {
		upBtn.enabled = (position > 0) ? true : false;
		downBtn.enabled = (position < myList.maxVerticalScrollPosition) ? true : false;
	} 

	private function scroll(direction:String):void {
		var target:Number
		var current:Number = myList.verticalScrollPosition;
		if (direction == 'up') {
			// find the top scroll position
			target = Math.max(current - myList.rowCount, 0);
		} else {
			// find the bottom scroll position
			target = Math.min(current + myList.rowCount, myList.maxVerticalScrollPosition);
		}
		var t:Tween = new Tween(this,current,target,1000);
	} 

]]>
</mx:Script>
<mx:VBox width="200" paddingLeft="10" paddingTop="10">
	<mx:Button id="upBtn" label="Scroll Up" click="scroll('up')" width="100%"/>
	<mx:List id="myList" dataProvider="{myData}" creationComplete="refreshButtons()" verticalScrollPolicy="off" width="100%"/>
	<mx:Button id="downBtn" label="Scroll Down" click="scroll('down')" width="100%"/>
</mx:VBox>


Add a Comment