Here is a multi-state button object with optional sound effects that some of you might find useful in your apps or as a template for creating your own custom controls.
Thanks go to Stephan Wicki at PlusTherm for allowing us to share this code (developed by the DroidScript team for PlusTherm).
//--- Usage Example -------------------------
app.LoadScript( "MultiButton.js" );
:
:
//Create tri-state power button.
var states = "Img/Grey.png,Img/Orange.png,Img/Green.png";
var sounds = "Snd/ClickOn.ogg,Snd/ClickOff.ogg";
btnPower = app.CreateMultiButton( states, sounds, 0.3, -1 );
btnPower.SetOnTouch( btnPower_OnTouch );
lay.AddChild( btnPower );
:
:
//Create bi-state heat button.
var states = "Img/HeatOff.png,Img/HeatOn.png";
var sounds = "Snd/ClickOn.ogg,Snd/ClickOff.ogg";
btnHeat = app.CreateMultiButton( states, sounds, 0.3, -1 );
btnHeat.SetMargins( 0.1,0,0,0 );
btnHeat.SetOnTouch( btnHeat_OnTouch );
lay.AddChild( btnHeat );
:
:
//--- MultiButton.js -----------------
//Add button to main app object.
app.CreateMultiButton = function( stateImages, sounds, width, height )
{
return new MultiButton( stateImages, sounds, width, height );
}
//Multi-state button.
function MultiButton( stateImages, clickSounds, width, height )
{
//Callbacks.
var onTouchCb = null;
//Get array of state images.
var images = [];
var list = stateImages.split(",");
//Load buttons state images to memory.
for( var i=0; i<list.length; i++ )
images.push( app.CreateImage( list[i], width, height ) );
//Create layout to contain button.
var lay = app.CreateLayout( "Frame" );
//Create visible image control in layout.
var img = app.CreateImage( list[0], width, height );
img.SetOnTouchDown( _Cb(this,"OnTouchDown") );
img.SetOnTouchUp( _Cb(this,"OnTouchUp") );
lay.AddChild( img );
//Set click sounds if provided.
var players = [];
var list = clickSounds.split(",");
for( var i=0; i<list.length; i++ ) {
players[i] = app.CreateMediaPlayer();
players[i].SetFile( list[i] );
}
//Squeeze image on touch down.
this.OnTouchDown = function() {
img.Scale( 0.9,0.9 );
app.Vibrate( "0,30" );
if( players[0] ) players[0].Play(0);
}
//Expand image on touch up.
this.OnTouchUp = function()
{
setTimeout( function() {
img.Scale( 1,1 );
app.Vibrate( "0,30" );
if( players[1] ) players[1].Play(0);
if( onTouchCb ) onTouchCb();
}, 100 );
}
//Allow user to set callback.
this.SetOnTouch = function( callback ) {
onTouchCb = callback;
}
//Set state of button (change image).
this.SetState = function( num )
{
img.SetImage( images[num] );
}
this.SetMargins = function(left,top,right,bottom) {
lay.SetMargins(left,top,right,bottom);
}
//Return the layout.
}