DroidScript wiki

(was AndroidScript) unofficial documentation by the community

User Tools

Site Tools


sample_code:numeric_input

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sample_code:numeric_input [2015/01/21 17:03] (current)
stevegarman created
Line 1: Line 1:
 +====== Get numbers from user ======
 +It's not really practical to force a user to enter a number.
  
 +It is, however fairly easy to check the input, either immediately it is entered or when trying to perform calculations.
 +
 +This code demonstrates how it can be done, using a function toFloat
 +
 +<code JavaScript get number.js>​
 +// global
 +var edt1,​edt2,​edt3,​edt4
 +//​Called when application is started.
 +function OnStart()
 +{
 +    //​Create a layout
 +    var lay = app.CreateLayout( "​linear",​ "​FillXY"​ );​    
 +
 +    //​Create 4 textEdits and add them to layout.
 +    edt1 = app.CreateTextEdit( "",​-1,​-1,"​Number"​ );​
 +    edt1.SetHint("​Number"​);​
 +    lay.AddChild( edt1 );​
 +    edt2 = app.CreateTextEdit( "",​-1,​-1,"​Number"​ );​
 +    edt2.SetHint("​Multiply by"​);​
 +    lay.AddChild( edt2 );​ 
 +    edt3 = app.CreateTextEdit( "",​-1,​-1,"​Number"​ );​
 +    edt3.SetHint("​Divide by"​);​
 +    lay.AddChild( edt3 );​
 +    edt4 = app.CreateTextEdit( "",​-1,​-1,"​Number"​ );​
 +    edt4.SetHint("​Add"​);​
 +    lay.AddChild( edt4 );​
 +
 +    //​Create a "​Calculate"​ button
 +    var btn = app.CreateButton("​Calculate"​);​
 +    btn.SetOnTouch(btnOnTouch);​
 +    lay.AddChild(btn);​
 +    //​Add layout to app.    
 +    app.AddLayout( lay );​
 +    
 +}
 +
 +function btnOnTouch()
 +{
 +    var res = toFloat(edt1)
 +        * toFloat(edt2)
 +        /​ toFloat(edt3)
 +        + toFloat(edt4);​
 +    if(isNaN(res)) app.Alert("​The result is not a valid number"​)
 +    else app.Alert(res);​
 +}
 +
 +function toFloat(control) 
 +{
 +//​take a control (probably a TextEdit) and return its text as a number
 +    var value = control.GetText();​
 +    var ret = +(value.replace(',','​.'​));​
 +    if( isNaN(ret) ) app.ShowPopup(value +"​ is not a number"​);​
 +    return ret;​
 +}
 +
 +</​code>​
sample_code/numeric_input.txt · Last modified: 2015/01/21 17:03 by stevegarman