BasicIDE B4AScript Language Extensions v5.70

Script Events

General Functions

String, Numeric and Logical Functions

Activity and Device Functions

Phone Interaction Functions

Array Functions

Collection Functions

File Functions

GNSS Functions

Sensor Functions

Add and Remove View Functions

Shared View Functions

CheckBox, RadioButton and ToggleButton Functions

EditText Functions

Graphics and Image Functions

ImageView and ScaleImageView Functions

ListView Functions

ListView and Spinner Functions

ProgressBar Functions

Regular Expression Functions

ScrollView Functions

SeekBar Functions

Spinner Functions

TabHost Functions

Table Functions

Textview Functions

Timer Functions

User Interaction Functions

Async User Interaction Functions

Debugging Functions

Color Names and Constants

KeyCode Functions and Constants

Gravity Constants

Typeface Constants

Sensor Constants


Contents


SCRIPT EVENTS

If a Sub of any of these names are defined in the program then it will be called at the appropriate time.
The 'who' parameter will be set to the lower cased name of the view that caused the event.
Use Template.b4s as a starting point for a project and enter the event code as needed.

Activity_Create
There is no supported Activity_Create sub.
Instead the inital block of code block from the beginning of the script up to the first Sub statement is run.
GetFirstTime returns True the first time the initial code block is run after a program is started.
This block of code will be run again whenever the Activity is re-created

Activity_Pause(userclosed)
"Sub activity_pause(userclosed)" is called if implemented. userclosed will be True if the [Back] button was pressed.

Activity_Resume
"Sub activity_resume" is called if implemented.

Activity_Keypress(keycode)
"Sub activity_keypress(keycode)" is called if implemented.
Keycode will contain the system key code of the key pressed, and may be tested using the KEYCODE FUNCTIONS and KEYCODE CONSTANTS.
Return True from Activity_Keypress(keycode) to consume the keystroke (ie. not allow the system to continue processing it.)

Example:
Sub Activity_Keypress(keycode)
  # process numbers only, all others ignored
  If keycode = Key_isNumber(keycode)
    # process the keystroke here...
    # then consume the keystroke
    Return true
  End If
End Sub

Button_Click(who)
All Button Click events are vectored to a single BasicLib sub "Sub button_click(who)".

Check_CheckedChange(who, checked)
All Checkbox CheckedChange events are vectored to a single BasicLib sub "Sub check_checkedchange(who, checked)".

Edit_EnterPressed(who)
All EditText EnterPressed events are vectored to a single BasicLib sub "Sub edit_enterpressed(who)".

Edit_TextChanged(who, oldtext, newtext)
All EditText TextChanged events are vectored to a single BasicLib sub "Sub edit_textchanged(who, oldtext, newtext)".

Edit_FocusChanged(who, hasfocus)
All Edittext FocusChanged events are vectored to a single BasicLib sub "Sub edit_focuschanged(who, hasfocus)".

HSV_Changed(who, position)
All HorizontalScrollView ScrollChanged events are vectored to a single BasicLib sub "Sub hsv_scrollchanged(who, position)".

ImageView_Click(who)
All ImageView Click events are vectored to a single BasicLib sub "Sub imageview_click(who)".

ImageView_LongClick(who)
All ImageView LongClick events are vectored to a single BasicLib sub "Sub imageview_longclick(who)".

Label_Click(who)
All Label Click events are vectored to a single BasicLib sub "Sub label_click(who)".

Gnss_Status(beidou, galileo, glonass, gps)
GNSS Status events are vectored to BasicLib sub "Gnss_Status(beidou, galileo, glonass, gps)"'

Gnss_LocationChanged(latitude, longitude, ukgridref)
GNSS LocationChanged events are vectored to BasicLib sub "Sub Gnss_LocationChanged(latitude, longitude, ukgridref)".

Listview_ItemClick(who, position, value)
All ListView ItemClick events are vectored to a single BasicLib sub "Sub listview_itemclick(who, position, value)".

Menu_Click(menutext)
All menu item click events are vectored to a single BasicLib sub "Sub menu_click(menutext)".

Panel_Click(who)
All Panel Click events are vectored to a single BasicLib sub "Sub panel_click(who)".

Radio_CheckedChange(who, checked)
All RadioButton CheckedChange events are vectored to a single BasicLib sub "Sub radio_checkedchange(who, checked)".

ScaleImageView_Click(who)
All ScaleImageView Click events are vectored to a single BasicLib sub "Sub scaleimageview_click(who, viewx, viewy, imagex, imagey)".

ScaleImageView_LongClick(who)
All ScaleImageView LongClick events are vectored to a single BasicLib sub "Sub scaleimageview_longclick(who, viewx, viewy, imagex, imagey)".

Seekbar_ValueChanged(who, userchanged)
All SeekBar ValueChanged events are vectored to a single BasicLib sub "Sub seekbar_valuechanged(who, value, userchanged)".

Sensor_Changed(who, value0, value1, value2)
All Sensor SensorChanged events are vectored to a single BasicLib sub "Sensor_Changed(who, value0, value1, value2)".

Spinner_ItemClick(who, position, value)
All Spinner ItemClick events are vectored to a single BasicLib sub "Sub spinner_itemclick(who, position, value)".

Tabhost_TabChanged(who)
All TabHost TabChanged events are vectored to a single BasicLib sub "Sub tabhost_tabchanged(who)".

Table_CellClick(who, col, row)
All Table CellClick events are vectored to a single BasicLib sub "Sub table_cellclick(who, col, row)".

Table_CellLongClick(who, col, row)
All Table CellLongClick events are vectored to a single BasicLib sub "Sub table_celllongclick(who, col, row)".

Table_HeaderClick(who, col)
All Table Table_HeaderClick events are vectored to a single BasicLib sub "Sub table_headerclick(who, col)".

Table_HeaderLongClick(who, col)
All Table Table_HeaderLongClick events are vectored to a single BasicLib sub "Sub table_headerlongclick(who, col)".

Table_ScrollChanged(who, pox, posy)
All Table ScrollChanged events are vectored to a single BasicLib sub "Sub table_scrollhanged(who, posx, posy)".

Timer_Tick
All Timer tick events are vectored to a single BasicLib sub "Sub timer_tick".

Toggle_Changed(who, checked)
All ToggleButton CheckedChange events are vectored to a single BasicLib sub "Sub toggle_changed(who, checked)".

Event Templates
Here are all the event Sub templates to copy and paste if desired.
Note that code for these events is already included in the Template.b4s file.

Sub activity_pause(userclosed)
End Sub

Sub activity_resume
End Sub

End Sub

Sub button_click(who)
End Sub

Sub check_checkedchange(who, checked)
End Sub

Sub edit_enterpressed(who)
End Sub

Sub edit_textchanged(who, old, new)
End Sub

Sub edit_focuschanged(who, hasfocus)
End Sub

Sub gnss_status(beidou, galileo, glonass, gps)
End Sub

Sub gnss_locationchanged(latitude, longitude, ukgridref)
End Sub

Sub hsv_scrollchanged(who, position)
End Sub

Sub imageview_click(who)
End Sub

Sub imageview_longclick(who)
End Sub

Sub label_click(who)
End Sub
Sub listview_itemclick(who, pos, value)
End Sub

Sub menu_click(menutext)
End Sub

Sub panel_click(who)
End Sub

Sub radio_checkedchange(who, checked)
End Sub

Sub scaleimageview_click(who, viewx, viewy, imagex, imagey)
End Sub

Sub scaleimageview_longclick(who, viewx, viewy, imagex, imagey)
End Sub

Sub seekbar_valuechanged(who, pos, value)
End Sub

Sub sensor_changed(who, value0, value1, value2)
End Sub

Sub spinner_itemclick(who, pos, value)
End Sub

Sub tabhost_tabchanged(who)
End Sub

Sub Sub table_cellclick(who, col, row)
End Sub

Sub Sub table_celllongclick(who, col, row)
End Sub

Sub Sub table_headerclick(who, col)
End Sub

Sub Sub table_headerlongclick(who, col)
End Sub

Sub Sub table_scrollchanged(who, posx, posy)
End Sub

Sub timer_tick
End Sub

Sub toggle_changed(who, checked)
End Sub

Contents


GENERAL SYSTEM FUNCTIONS

ClipboardGetText As returnvalue
Returns True if the system clipboard conatains text.

ClipboardHasText As returnvalue
Returns any text on the system clipboard.

ClipboardSetText(text)

CloseApplication
On Android 4+ will close all the activities.
When called in a script this will exit the application without resuming the IDE activity.
AppClose in contrast will just close this activity and return to the Main activity.

IIf(condition, truepart, falsepart) As returnvalue
IIf is a function that performs an If...Else...End If as a one line statement.
IIf has 3 parts: a condition, a True part and a False part.
The condition is evaluated, and if it evaluates true, the true part is returned, otherwise the false part is returned.
It should not replace an If block that makes tests to ensure an error will not result.
This is because both True part and False part are evaluated when the function is called.
Example:
# instead of this...
If a = 5 Then
  b = b + 1
Else
  b = b - 1
Endif
# use this...
b = b + IIf(a = 5, 1, -1)

HideKeyboard
Hides the soft keyboard.

Contents


STRING, NUMERIC AND LOGICAL FUNCTIONS

FormatNumber(Number, MinimumIntegers, MaximumFractions) As returnvalue
Converts the specified number to a string.
This is an exposure of the B4A NumberFormat keyword to BAScript.
The string will include at least MinimumIntegers and at most MaximumFractions digits.
Example: Log(NumberFormat(12345.6789, 0, 2)) = "12345.68", Log(NumberFormat(1, 3 ,0)) = "001"
Note there is also the B4AScript Format function that formats numbers using a Java DecimalFormat object.

FormatNumber2(Number, MinimumIntegers, MaximumFractions, MinimumFractions, UseGrouping) As returnvalue
Converts the specified number to a string.
This is an exposure of the B4A NumberFormat2 keyword.
The string will include at least MinimumIntegers, at most MaximumFractions and at least MinimumFractions digits.
UseGrouping if True groups every three integers.
Example: Log(NumberFormat2(12345.67, 0, 3, 3, False)) = "12345.670"
Note there is also the B4AScript Format function that formats numbers using a Java DecimalFormat object.

IntToBinary(intvalue) As returnvalue
This function implements the conversion of Int32 integer values to binary literal strings.
This is an exposure of the B4A Bit.ToBinaryString function.

IntToHex(intvalue) As returnvalue
This function implements the conversion of Int32 integer values to hexadecimal literal strings.
This is an exposure of the B4A Bit.ToHexString function.

IntFromHex(hexstring) As returnvalue
Unlike the Basic4ppc BasicLib library the B4A BasicLib library does not support Hex literals.
This function implements the conversion of hexadecimal literal strings to Int32 values.
Int32 is used as the basis for conversion as hex numbers are primarily used for convenient representation of ARGB colour values.
The signed Int32 values returned from IntFromHex will round trip to double values and back.
The formats, 'abcd', '#abcd' and '0xabcd' are accepted and all are case insensitive.
If numstring exceeds eight characters only the rightmost eight are used in the conversion.
ParseInt can also convert strings to integer values using a specified radix.

ParseInt(numstring, radix) As returnvalue
Parses numstring as an unsigned integer using the specified integer radix.
This is an exposure of the B4A Bit.ParseInt function.
Radix should be between 2 and 36.
Unlike IntFromHex the resulting integer is always positive.
A NumberFormatExeption error occurs if the resulting Int32 value would represent a negative number.
If numstring starts with a minus chaacter the resulting integer value will be negative,

SBAppend(text)
Append 'text' to the end of the StringBuilder object.

SBInitialize
There is a single StringBuilder object which can be used as many times as needed.
Initialize (or reinitialize) the StringBuilder object.
If the StringBuilder object is already initialized, it will be reinitialized and its text reset to blank.
StringBuilder contents persist over Activity pause and resume and when chaining programs.

SBInsert(offset, text)
Insert 'text' at the offset specified, in the StringBuilder object.

SBLength As returnvalue
Returns the length of the text in the StringBuilder object.

SBRemove(start, end)
Remove the text starting at 'start' offset up to, but not including, the 'end' offset, of the StringBuilder object.

SBToString As returnvalue
Returns the text in the StringBuilder object.

StrTrim(string) As returnvalue
Returns a string that has had white space trimmed from the start and end of the passed string.
Ex. StrTrim(" 123 ") returns "123"

ShiftLeft(intvalue, places) As returnvalue
Shifts intvalue left by the number of places.

ShiftRight(intvalue, places) As returnvalue
Shifts intvalue right by the number of places.

ShiftRightUnsigned(intvalue, places) As returnvalue
Shifts intvalue right unsigned by the number of places.

Contents


ACTIVITY AND DEVICE FUNCTIONS

As well as the following functions the standard view functions for the activity may be be accessed by
 using the pre-allocated view name 'Activity'.

Each script runs in its this 'Script' activity so 'activity' and 'script' are synonymous in this help documentation.

ActivityFinish
Closes the activity and return directly to the editor. This may sometimes be required but should be avoided.
Calling this bypasses the normal Blib_Ended code that will display any Print output and any error message.
Close a script without events by calling CloseAfterThis and close a script with events by AppClose.

CanCall(subname) As returnvalue
Returns True if Sub subname exists and can be called by the current program otherwise returns False.

Chain(scriptname)
Close the activity and recreate it running the new script identified by scriptname.
If scriptname does not end with the suffix '.b4s' then Chain will add that suffix to scriptname.
The new script is loaded from the folder specified in the ScriptDir process global variable.
BasicIDE sets ScriptDir to File.DirRootExternal & "/BasicIDE". Stand-alone programs may want to change this.
The Map, List, Stringbuilder and Global values saved by SaveArray/Global are preserved for the new program to use.
GetFirstTime and GetRestarting will both be True in the new activity.

GetActivityHeight As returnvalue
Get the actual height of the activity. This is the same value as GetHeight('Activity')
This is not necessarily the same as the physical display height from GetLayoutValues unless the activity is full-screen.

GetActivityWidth As returnvalue
Get the actual width of the activity. This is the same value as GetWidth('Activity')
This is not necessarily the same as the physical display width from GetLayoutValues unless the activity is full-screen.

CloseAfterThis
Closes the activity and returns directly to the editor. This may be required by a Non-UI script.
Calling this bypasses the normal Blib_Ended code that will display any Print output and any error message.
Close a script without events by calling CloseAfterThis and close a script with events by AppClose.

CloseMenu
Closes the Activity menu. This is added for symmetry with OpenMenu but seems of little practical use.

GetAllViews(arrayname)
Returns the names of all the current views in the named array.
The array does not need to be declared with Dim, if it does not already exist it will be created.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

GetFirstTime As returnvalue
GetFirstTime is usually used by the initial code block for this script that is run whenever the Script activity is created.
GetFirstTime is almost the equivalent of the parameter FirstTime in Activity_Create for B4A.
B4A FirstTime cannot be used as it is only True for the first invocation of the Script activity by the IDE.
Thereafter whenever the IDE restarts a script after editing it B4A FirstTime will be always be False.
GetFirstTime is set True when the IDE starts a script or when a running script Chains to another script.
GetFirstTime is set to False after the next Activity_Resume completes so is True in the Resume event.
If GetFirstTime is False then the activity has been recreated after a device rotation or for some other reason.
If GetRestarting is False then this script is the invocation of the first script of a program by the IDE.
Future invocations of this script by chaining from another will have both GetFirstTime and GetRestarting set True.

GetLayoutValues As returnvalue
Get the layout values for this device in a comma separated string "width, height, scale".
The "width and height values seem unhelpful as they do not reflect either the physical screen nor the activity size.
The scale value is the device scale value of ScreenDpi/160. This is the value also returned by GetScreenScale
Using the GetWidth and GetHeight activity values seems much more useful to a program when placing views.

GetOrientation As returnvalue
Returns the orientation of the device as either 'Portrait' or 'Landscape'.

GetRestarting As returnvalue
Returns True if this script is being restarted because the script called RestartActivity.
It is also True if this script called Chain to start another script.
This is set to False after the next Activity_Resume completes so is True in the next Pause event.
It will also be True when the next intial code block of either the restarted or the chained script runs.
If the script was started by being chained from another GetFirstTime is also True.
Thereafter re-creations of this script will find this is False.

GetScreenScale As returnvalue
Get the scaling value (density) for this device which is ScreenDpi/160.

OpenMenu
Opens the Activity menu.

ResetState(stateid)
Remove the stored state of the views of the activity identified by stateid.
RestoreState(stateid) will now return False as no state is now saved.

RestartActivity
This closes and restarts the Activity so Activity_Create will run again.
Note that Pause is now called with UserClosed in the Pause event set True.
GetRestarting can be used to determine if the activity was restarted.
GetRestarting is set to False after the next Activity_Resume completes so is True in the Pause and Resume events.

RestoreState(stateid, timeout) As returnvalue
Restore the saved state of the views of the activity identified by stateid.
stateid is an arbitrary name that should uniquely identify the Activity whose state was saved.
Returns True if the view states are restored otherwise returns False.
If the last save was longer ago than timeout then don't restore.
Pass 0 for an unlimited timeout period.

SaveState(stateid)
Save the state of the views of the current activity with the saved state identified by stateid.
stateid is an arbitrary name that should uniquely identify the Activity whose state is saved.
This eases the problem of saving and restoring the state of views when the device is rotated.

SetActivityBackground(orientation, radius, colorsarrayname) As returnvalue
Set the Background property of the Activity to the GradientDrawable.
Returns false if less than two colors are in the array otherwise returns true.
Orientation can be one of the following:
"TOP_BOTTOM", "TR_BL" (Top-Right to Bottom-Left), "RIGHT_LEFT", "BR_TL" (Bottom-Right to Top-Left)
"BOTTOM_TOP", "BL_TR" (Bottom-Left to Top-Right), "LEFT_RIGHT", "TL_BR" (Top-Left to Bottom-Right)

SetActivityTitle(title)
Sets the activity title text in the activity's title label.

SetOrientation(orientation)
Sets the available orientations of the screen for this activity.
Orientation is -1 = unspecified, 0 = Landscape, 1 = Portrait.

Contents


ARRAY FUNCTIONS

FillArray(arrayname, start, length, value)
Fully or partially fills the specified array with the specified value.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

SearchArray(arrayname, value) As returnvalue
Searches the specified array for the specified value using the binary search algorithm.
The array must be sorted into ascending order using cCaseSensitive or cNumbers otherwise the result may not be accurate.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

SortArray(arrayname, sorttype)
Sort the specified array into ascending order in the specified manner.
One of cCaseSensitive (0), cCaseUnensitive (1) or cNumbers (2).
cCaseInsensitive is also accepted as a synonym for cCaseUnensitive.
Note that for use with SearchArray cCaseSensitive or cNumbers should be used otherwise the result may not be accurate.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

SortArrays2(sortarrayname, otherarrayname, sorttype)
Sort the first specified array into ascending order in the specified manner.
One of cCaseSensitive (0), cCaseUnensitive (1) or cNumbers (2).
cCaseInsensitive is also accepted as a synonym for cCaseUnsensitive.''
The second array will be kept 'in step' with the first by similarly reordering its contents.
One obvious use for this is to sort the keys array of a MapToArrays while keeping the values array in step.
Note that for use of the sorted array with SearchArray cCaseSensitive or cNumbers should be used otherwise the result may not be accurate.
A common mistake is to try to use a reference to an array, arrayname is the name of the array as a String.

Contents


COLLECTION FUNCTIONS

There is a single Map object which contains key value pairs and can be indexed in insertion order.
Map key lookups are case-sensitive.
Map contents persist over Activity pause and resume and when chaining programs.

There is a single List object which can grow or shrink in size according to the number of items.
List contents persist over Activity pause and resume and when chaining programs.

ListAdd(item)
Add the item to the List.

ListClear
Clears the contents of the List.

ListFromArray(arrayname)
Sets the List to the contents of the named array.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

ListGet(index) As returnvalue
Get the item at index in the List.

ListInsertAt(index, item)
Inserts the item into the list at index.

ListRemoveAt(index)
Removes the item at index from the List.

ListSize As returnvalue
Returns the number of items in the List.

ListSort(ascending)
Case-sensitively sorts the items in the List, in ascending order if ascending is True.

ListSortCaseInsensitive(ascending)
Case-insensitively sorts the items in the List, in ascending order if ascending is True.

ListToArray(arrayname)
Sets the contents of the named array to those of the List.
The array does not need to be declared with Dim, if it does not already exist it will be created.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

MapClear
Clears the contents of the Map

MapFromArrays(keysarrrayname, valuesarrayname)
Clear the Map then set it to the keys and values in the named arrays

MapGet(key) As returnvalue
Get the value at the key/value item in the Map or an empty string if the key is not present.

MapKeyAt(index) As returnvalue
Returns the key of the item at index or an empty string if the item is not present.
The index values organise the items in order of insertion.

MapPut(key, value)
Puts the key and value as an item into the Map.

MapSize As returnvalue
Returns the number of items in the Map.

MapToArrays(keysarrrayname, valuesarrayname)
Set the keys and values arrays to the contents of the Map.
The arrays do not need to be declared with Dim, if they do not already exist they will be created.

MapValueAt(index) As returnvalue
Returns the value of the item at index or an empty string if the item is not present.
The index values organise the items in order of insertion.

RestoreArray(arrayname)
Restore the saved contents of the named array.
This can used to persist program values during Activity pause and resume and when chaining programs.
The array does not need to be declared with Dim, if it does not already exist it will be created.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

RestoreGlobal(globalname)
Restore the saved contents of the named global variable.
This can used to persist program values during Activity pause and resume and when chaining programs.
A common mistake is to try to use a reference to the variable, globalname is the name of the variable as a String.

SaveArray(arrayname)
Save the contents of the named array so it can be restored on activity re-creation when GetFirstTime is False.
All the program arrays and global variables are reset when the first code block is run again to recreate the views.
This can used to persist program values during Activity pause and resume and when chaining programs.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.

SaveGlobal(globalname)
Save the contents of the named global variable so it can be restored on activity re-creation when GetFirstTime is False.
All the program arrays and global variables are reset when the first code block is run again to recreate the views.
This can used to persist program values during Activity pause and resume and when chaining programs.
A common mistake is to try to use a reference to the variable, globalname is the name of the variable as a String.

Contents


FILE FUNCTIONS

FileCopy(sourcedir, sourcefilename, destdir, destfilename) As returnvalue
Copies the SourceFilename file in the SourceDir directory to the DestFilename directory and sets the name to DestFilename.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

FileDelete(dir, filename) As returnvalue
Deletes the specified file. If the file name is a directory then it must be empty in order to be deleted.
Returns true if the file was successfully deleted otherwise False.
Files in the assets folder cannot be deleted.
If an exception was raised the exception message is returned instead of True or False

FileDirAssets As returnvalue
Returns a reference to the files added with the Files Manager. These files are read-only.
This is actually the string "AssetsDir" which B4A OpenInput(Dir, String) treats specially as a Dir parameter.
This is why FileGetPath does not support FileDirAssets as it then lacks the unique name that OpenInput looks for.

FileDirDefaultExternal As returnvalue
Returns the application default external folder which is based on the package name.
The folder is created if needed.

FileDirInternal As returnvalue
Returns the internal private storage folder.
FileSafeDirDefaultExternal is a better alternative.

FileDirInternalCache As returnvalue
Returns the internal private storage cache folder.
This data will be deleted automatically if the device runs low on storage.

FileDirRootExternal As returnvalue
Returns the root folder of the external storage media.
Apps targetting API 29+ will not get permission to access FileDirRootExternal, even with the STORAGE permission.
BasicIDE currently target API 28 for this reason

FileExists(dir, filename) As returnvalue
Returns true if the specified FileName exists in the specified folder.
Note that the Android file system is case sensitive.

FileExternalWritable As returnvalue
Tests the external media, or SDCard (some devices call this Internal Storage), for readibility and writability.
Returns True if the storage can be written and read otherwise False.

FileGetPath(dir, filename) As returnvalue
Returns the fully qualified pathname of the filename. This does not support the Assets directory.

FileIsDirectory(dir, filename) As returnvalue
Tests whether the specified file is a directory.

FileListFiles(dir, filesarrayname) As returnvalue
Fills an array with a list with all the files and directories which are stored in the specified path.
Returns an empty string if successful otherwise the exception message of the exception that was raised.
The array does not need to be declared with Dim, if it does not already exist it will be created.

FileMakeDir(parentdir, dir) As returnvalue
Creates the given folder (dir can be a path like "dir1/dir2", it creates all folders as needed).
Returns an empty string if successful otherwise the exception message of the exception that was raised.

FileReadList(dir, filename, listarrayname) As returnvalue
Reads the entire file and fills a named array with all lines as strings.
Returns an empty string if successful otherwise the exception message of the exception that was raised.
The array does not need to be declared with Dim, if it does not already exist it will be created.

FileReadString(dir, filename) As returnvalue
Reads the entire file and returns it as a string if successful.
Otherwise returns the exception message of the exception that was raised prefixed by !ERROR!.

FileRename(dir, oldfilename, newfilename) As returnvalue
Renames the old filename to the new filename.
Note that this method uses the B4A File.Copy and File.Delete methods internally.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

FileWriteList(dir, filename, listarrayname) As returnvalue
Writes each item in the List as a single line to a new file.
Note that a value containing CRLF will be saved as two lines which will return two items when read with ReadList.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

FileWriteString(dir, filename, text) As returnvalue
Writes the given text to a new file.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

FileSafeDirDefaultExternal(subfolder) As returnvalue
Returns the path To the app's default folder on the secondary storage device.
The path to File.DirInternal will be returned if there is no secondary storage available.
This is a better alternative to File.DirDefaultExternal as it requires no permission.
SubFolder is the name of sub folder that will be created for your app. Pass an empty string if not needed.

Contents


GNSS FUNCTIONS

The GNSS is automatically disabled on activity pause and, if it was running when paused, re-enabled on activity resume.
There are two events raised by the GNSS when running, Status and locationChanged.

GNSS LocationChanged events call Sub Gnss_LocationChanged(latitude, longitude, ukgridref).
Latitude and longitude are WGS84 coordinates and ukgridref is a 5 digit UK National Grid code with 1m resolution.

GNSS Status events call script Sub Gnss_Status(beidou, galileo, glonass, gps).
Each Gnss_Status parameter is a string in the format 'numberused/numbervisible'.
This event, even if not passed to a script event, creates a list of satellites visible and their status.
GNSSSats returns the length of this list and GNSSSatAt returns a comma separated string of satellite data.
This list of satellites is sorted by PRN so the satelites of each constellation are contiguous.
Beidou PRNs have 200 added and are in the range 201 to 237.
Galileo PRNs have 300 added and are in the range 301 to 326.
Glonass FCNs/OSNs have 64 added and are in the range 65 to 88 or possibly 157 to 172.
GPS PRNs are unadjusted and are in the range 1 to 32.
The list is fully updated before the Gnss_Status event Sub is invoked.
It can be accessed from anywhere and at any time.

GNSSAccuracy As returnvalue
Returns the accuracy of the GNSS fix.

GNSSAltitude As returnvalue
Returns the altitude of the GNSS fix.

GNSSAvailable As returnvalue
Returns True if GNSS is available on the device and the user has permitted its use.

GNSSRunning As returnvalue
Returns True if GNSS is presently enabled and running.

GNSSSats As returnvalue
Returns the number of satellites for which information is available.
The satellite information is held in a list sorted by unadjusted Prn.
Each satellite in the list can be accessed using GNSSSatAt.

GNSSSatAt As returnvalue
Returns the information for the satellite at index in the list of available satellites.
Returns a comma separated string containing 'Prn,Azimuth,Elevation,UsedInFix,Snr' for the satellite.
Curiously despite being declared as Float the azimuth and elevation appear to be integer values.

GNSSSatsVisible(constellation) As returnvalue
Return a comma separated string of the unadjusted PRNs of the satellites visible in constellation.
Prns used in the fix will be suffixed by an asterisk.
Beidou is 0 : Galileo is 1 : Glonass is 2 : GPS is 3

StartGNSS
Start the GNSS.

StopGNSS
Stop the GNSS.

These constants return the values needed for the GNSSSatsVisible functions
They may be used instead of hard coding numeric values.

GnssBeidou = 0
GnssGalileo = 1
GnssGlonass = 2
GnssGPS = 3

Contents


SENSOR FUNCTIONS

Sensor constants are available in B4Script to support the nine most common sensor types available on Android.
All SensorChanged events are vectored to a single BasicLib sub "Sensor_Changed(who, value0, value1, value2)".
Most sensors return either a single value or three values.
Some sensors may return more than three value which may be obtained by invoking GetSensorValues.
Light, Pressure, Temperature and Proximity return a single value found in value0 of the event parameters
Accelerometer, Magnetic, Orientation, Gyroscope and Gravity return three values, X, Y and Z in the event value0, value1 and value2 parameters.
For Orientation the parameter values are X = Yaw, Y = Pitch, Z = Roll
All the sensors that are available are returned by GetSensors.
The first three sensor values are available as parameters to the SensorChanged event.

AddSensor(sensortype, sensorname)
Make a sensor type available to the program.
sensortype is a Sensor constant or integer value to define the sensor type.
sensornameName is a string to identify the sensor to the progam. It will be returned lower-cased as 'who' in the Sensor_Changed event.
AddSensor should be called within a GetFirstTime conditional block so the sensor is added only once when the program is invoked.

GetSensors As returnvalue
Return a string containing details of all the sensor types available to the program.
Within the string the details for each sensor are enclosed by braces, {}, and terminated by a CRLF character.
Within the braces are values for the sensor: Sensor name, vendor, version, type, maxRange, resolution, power and minDelay.
These values are presented as comma separated declarations of the form: Sensor name="Some sensor", ...,type=1,...
Type is the integer value of the Sensor constant used to identify the sensor when invoking AddSensor.

GetSensorValues As returnvalue
Returns a list of the sensor values passed to the latest SensorChanged event as a comma separated string.

StartSensor(sensorname) As returnvalue
Start the sensor listening for changes.
Returns True if the sensor is supported otherwise False.
StartSensor should be called in Activity_Resume

StopSensor(sensorname)
Stop the sensor listening for changes.
StopSensor should be called in Activity_Pause.

Contents


ADD AND REMOVE VIEW FUNCTIONS

The Add view functions use four parameters; name, left, top, width, height, and parent.
Parent can be the Activity, a Panel or a Tab in a TabHost.
Parent should be an empty string (ie. "") if adding to the activity.

AddButton(buttonname, left, top, width, height, parent)
Add a Button to the activity or a panel.

AddCheckBox(checkboxname, left, top, width, height, parent)
Add a CheckBox to the activity or a panel.

AddEditText(edittextname, left, top, width, height, parent)
Add an EditText to the activity or a panel.

AddHorizontalScrollView(horizontalscrollname, left, top, width, height, parent)
Add a Horizontal ScrollView to the activity or panel.
The inner panel width is set to the given width, it can be changed later as required using GetPanel.

AddImageView(imagename, left, top, width, height, parent)
Add an ImageView to the activity or a panel.

AddLabel(labelname, left, top, width, height, parent)
Add a Label to the activity or a panel.

AddListView(listviewname, left, top, width, height, parent)
Add a ListView to the activity or a panel.

AddMenuItem(menutext)
Add a MenuItem to the Activity.

AddPanel(panelname, left, top, width, height, parent)
Add a Panel to the activity or a panel.
The Panel Elevation is set to 1 otherwise Labels (and maybe other views) can be drawn over it.
Use getElevation and SetElevation to solve any other such problems that might arise.

AddProgressBar(progressbarname, left, top, width, height, parent)
Add a ProgressBar to the activity or a panel.

AddRadioButton(radiobuttonname, left, top, width, height, parent)
Add a RadioButton to the activity or a panel.

AddScaleImageView(scaleimageviewname, left, top, width, height, parent)
Supported gestures are:
One finger drag to pan, Two finger pinch to zoom And double tap to zoom in And out.
Pan While zooming, seamless switch between pan And zoom And fling momentum after panning.
Quick scale (one finger zoom - quick double tap Then drag)  
The Click and LongClick event parameters are as follows.
The viewx and viewy parameters are the pixel position of the point clicked on the ScaleImageView itself.
The imagex and imagey parameters are the pixel position of the point clicked on the original full size image.

AddScrollView(scrollviewname, left, top, width, height, parent)
Add a ScrollView to the activity or a panel.
The inner panel height is set to the given height, it can be changed later as required using GetPanel.

AddScrollView2D(scrollviewname, left, top, width, height, parent)
Add a ScrollView2D to the activity or a panel.
The inner panel width is set to the given width, it can be changed later as required using GetPanel.
The inner panel height is set to the given height, it can be changed later as required using GetPanel.

AddSeekBar(seekbarname, left, top, width, height, parent)
Add a SeekBar to the activity or a panel.

AddSpinner(spinnername, left, top, width, height, parent)
Add a Spinner to the activity or a panel.
Note that you must add an item to a Spinner or it hangs on drop down.

AddTabHost(tabhostname, left, top, width, height, parent)
Add a TabHost to the activity or a panel.

AddTable2D(tablename, left, top, width, height, parent)
Add a Table to the activity or a panel. The Table is added with the default of 4 columns specified.
Call ResizeTable to change the number of columns in the Table.
The Table cam be sorted in ascending or descending order by tapping the header as long as EnableSort is True.

AddToggleButton(togglebuttonname, left, top, width, height, parent)
Add a ToggleButton to the activity or a panel.
Although SetText will set the displayed text of a ToggleButton when the state changes
the text set by SetTextOff/On appropriate to the state of the button will be displayed.
If SetTextOff/On are not invoked then the displayed texts default to ON and OFF.
An initial SetChecked call should be made after LoadLayout to set the state and displayed text.
BasicIDE Designer will include SetChecked(tglname, False) in LoadLayout.

RemoveAllViewsEntirely
Removes all views from the Activity and from the program.

RemoveView(viewname)
Removes the named view from its parent, but doesn't destroy it.
Used primarily for hiding a panel containing views to be used for popup help screens and custom input dialogs.

RemoveViewEntirely(viewname)
Completely remove the named view its parent and from the program. It will no longer be available to the program.

Contents


SHARED VIEW FUNCTIONS

These functions apply to all views except Table because it is not a real View object.
However Left, Right, Top, Bottom, Width, Height and Visible have special code to support using them on a Table.
These primarily exist so that autoscaling and designer scripts will work on Table as well as regular views.

There is a pre-allocated name 'Activity' for the activity that can also be used for these functions.

BringToFront(viewname)
Bring the named view to the front of the Z order.

GetBottom(viewname) As returnvalue
Get the Bottom property of the named view.

GetElevation(viewname) As returnvalue
Get the GetElevation property of the named view.
Some views may be unexepectedly drawn over other views. Elevation is probably to blame.
Use GetElevation and SetElevation to investigate and solve any such problems.

GetEnabled(viewname) As returnvalue
Get the Enabled property of the named view.

GetHeight(viewname) As returnvalue
Get the Height property of the named view.

GetLeft(viewname) As returnvalue
Get the Left property of the named view.

GetParent(viewname) As returnvalue
Get the lower cased name of the parent of the named view or an empty string if there is no parent.
If not the Activity the parent will always be a Panel.

GetPadding(viewname) As returnvalue
Get the padding values of the named view or an empty string if there is no padding.
The padding values are returned as a comma separated string.

GetRight(viewname) As returnvalue
Gets the Right property of the named view.

GetTop(viewname) As returnvalue
Get the Top property of the named view.

GetVisible(viewname) As returnvalue
Get the Visible property of the named view.

GetWidth(viewname) As returnvalue
Get the Width property of the named view.

Invalidate(viewname)
Invalidate the named view.
Invalidate graphics updates to a view through Canvas drawing routines so a CallDoEvents will repaint the View.
See GRAPHICS FUNCTIONS for more info.

IsView(viewname) As returnvalue
Returns true if the named view exists, otherwise false.

RequestFocus(viewname)
Set the focus to the named view. Only views with editable text and a cursor may receive focus.

SendToBack(viewname)
Send the named view to the back of the Z order.

SetBackground(viewname, radius, color)
Set the Background property of the named view to a ColorDrawable.

SetBackgroundGradient(viewname, orientation, radius, colorsarrayname) As returnvalue
Set the Background property of the named view to a GradientDrawable.
Returns false if less than two colors are in the array or name not found otherwise returns true.
Orientation can be one of the following:
"TOP_BOTTOM", "TR_BL" (Top-Right to Bottom-Left), "RIGHT_LEFT", "BR_TL" (Bottom-Right to Top-Left)
"BOTTOM_TOP", "BL_TR" (Bottom-Left t0 top-Right), "LEFT_RIGHT", "TL_BR" (Top-Left to Bottom-Right)

SetBackgroundImage(viewname) As returnvalue
Set the BackgroundImage of the view to the present bitmap. See GRAPHICS FUNCTIONS for more info.
Return true if both view and bitmap are initialised otherwise return false.

SetBottom(viewname, bottom)
Set the Bottom property of the named view.

SetColor(viewname, radius, color)
Set the Background property of the named view to a ColorDrawable.
This is the same as SetBackground.

SetElevation(viewname, elevation)
Set the Elevation property of the named view.
Some views may be unexepectedly drawn over other views. Elevation will probably be to blame.
Use GetElevation and SetElevation to investigate and solve any such problems.

SetEnabled(viewname, enabled)
Set the true/false Enabled property of the named view.

SetHeight(viewname, height)
Set the Height property of the named view.

SetLeft(viewname, left)
Set the Left property of the named view.

SetParent(viewname, parent)
Removes the named view from its existing parent, if any, and adds it to the specified parent.
If the new parent is not a Panel then the view is added to the Activity.
The view retains its original size and position values which may not be appropriate for the new parent.
You can add views to a ScrollView Panel obtained by GetPanel.
You can add views to a TabHost Tab using the panel name specified by AddTab.

SetPadding(viewname, paddingvalues)
Set the padding values of the named view.
The values are provided in paddingvalues as four integer values in a comma separated string.

SetRight(viewname, right)
Set the Right property of the named view.

SetTop(viewname, top)
Set the Top property of the named view.

SetVisible(viewname, visible)
Set the true/false Visible property of the named view.

SetWidth(viewname, width)
Set the Width property of the named view.

Contents


CHECKBOX, RADIOBUTTON AND TOGGLEBUTTON FUNCTIONS

CheckBox, RadioButton and ToggleButton support Set/GetChecked in addition to the Shared View functions.
Note that ToggleButton will display text assigned by SetText but this will be overwritten when the state changes.

GetChecked(viewname) As returnvalue
Get the Checked state of a CheckBox, RadioButton or ToggleButton.

SetChecked(viewname, checkedstate)
Set the Checked state of a CheckBox, RadioButton or ToggleButton.

SetTextOff(togglebuttonname, text)
Sets the text that will appear in the OFF mode of a ToggleButton.

SetTextOn(togglebuttonname, text)
Sets the text that will appear in the ON mode of a ToggleButton.

Contents


EDITTEXT FUNCTIONS

EditText supports these functions in addition to the View and TextView functions.

GetSelectionStart(edittextname) As returnvalue
Gets the selection start position (or the cursor position) of the EditText.
Returns -1 if there is no selection or cursor.

SelectAll(edittextname)
Selects all text of the named edittext view.

SelectText(edittextname, selectionstart, selectionlength)
Selects text within the named edittext, starting at offset selectionstart and extending selectionlength characters.

SetForceDoneButton(edittextname, forcestate)
Force the EditText virtual keyboard action key to display Done by setting this value to True.

SetHint(edittextname, hinttext)
Set the text that will appear when the EditText is empty.

SetHintColor(edittextname, hintcolor)
Set the color of the text that will appear when the EditText is empty.

SetInputType(edittextname, inputtype)
Set the value of the EditText InputType property.
NONE = 0; TEXT = 1; NUMBERS = 2; _PHONE = 3; DECIMAL_NUMBERS = 12290;

SetPasswordMode(edittextname, state)
Set the true or false value of the EditText PasswordMode property.

SetSelectionStart(edittextname, startposition)
Sets the selection start position (or the cursor position) of the EditText.

SetSingleLine(edittextname, singlelinestate)
Set the true/false value of the EditText SingleLine property.

SetWrap(edittextname, wrapstate)
Set the true/false value of the EditText Wrap property.

Contents


GRAPHICS AND IMAGE FUNCTIONS

There is a single bitmap object, which can be initialised from an image file or as a new mutable bitmap.
There is a single canvas object, which can be initialised on any view, or on a mutable bitmap.
Both the bitmap and canvas objects may be reinitialised as many times as needed.
Rectangles are assumed to be the names of a BasicLib array of rank 4 with the x,y coordinates of two points.
The array items are ordered as left(0), top(1) of the upper left point and, right(2) and bottom(3) of the lower right point.
Points are assumed to be consecutive pairs of x,y coordinates in an array ordered as x(2n+0) and y(2n+1).
The drawings will only be updated after a call to ParentView.Invalidate.

BitmapHeight As returnvalue
Get the height of the current bitmap.

BitmapInit(dir, filename)
(Re)initialise the bitmap to a graphic file.

BitmapInitImage(imageviewname)
(Re)initialise the bitmap to the bitmap of an ImageView.

BitmapInitMutable(width, height)
(Re)initialise the bitmap to a mutable bitmap.

BitmapWidth As returnvalue
Get the width of the current bitmap.

CanvasInit(viewname)
(Re)initialise the canvas object on any View.

CanvasInit2
The one canvas can also be reinitialised on a mutable Bitmap if the sole Bitmap object is one.

DrawBitmap(srcrectarrayname, destrectarrayname) As returnvalue
Draws the present bitmap.
SrcRect - The rectangular area of the Bitmap that will be drawn.
DestRect - The rectangular area that the Bitmap will be drawn to.
Returns false if more or less than two points are in the rectangle arrays otherwise returns true.

DrawBitmapFlipped(srcrectarrayname, destrectarrayname, vertically, horizontally) As returnvalue
Draws the present bitmap either horizontally, vertically or both.
SrcRect - The rectangular area of the Bitmap that will be drawn.
DestRect - The rectangular area that the Bitmap will be drawn to.
Returns false if more or less than two points are in the rectangle arrays otherwise returns true.

DrawBitmapRotated(srcrectarrayname, destrectarrayname, degrees) As returnvalue
Draws the present bitmap rotated.
SrcRect - The rectangular area of the Bitmap that will be drawn.
DestRect - The rectangular area that the Bitmap will be drawn to.
Returns false if more or less than two points are in the rectangle arrays otherwise returns true.

DrawCircle(x, y, radius, color, filled, strokewidth)
Draws a circle.

DrawColor(color)
Fills the entire canvas with the given color.

DrawLine(x1, y1, x2, y2, color, strokewidth)
Draws a line.

DrawOval(rectarrayname, radius, color, filled, strokewidth) As returnvalue
Draws an ellipse.
Returns false if more or less than two points are in the array otherwise returns true.

DrawRotatedOval(rectarrayname, radius, color, filled, strokewidth, degrees) As returnvalue
Draws a rotated ellipse.
Returns false if more or less than two points are in the array otherwise returns true.

DrawPath(pointsarrayname, color, filled, strokewidth) As returnvalue
Draws a set of connected lines from the points provided in a named array.
Returns false if less than two points are in the array otherwise returns true.

DrawPoint(x, y, color)
Sets a single pixel to the specified color.

DrawRect(rectarrayname, color, filled, strokewidth) As returnvalue
Draws a rectangle from the points provided in a named array.
Returns false if more or less than two points are in the array otherwise returns true.

DrawRectRotated(rectarrayname, color, filled, strokewidth, degrees) As returnvalue
Draws a rotated rectangle from the points provided in a named array and a specified angle.
Returns false if more or less than two points are in the array otherwise returns true.

DrawText(text, x, y, textsize, textcolor, align)
Draw text. Align is one of the following values: "LEFT", "CENTER", "RIGHT".

DrawTextRotated(text, x, y, textsize, textcolor, align, degrees)
Draw text. Align is one of the following values: "LEFT", "CENTER", "RIGHT".

Contents


IMAGEVIEW AND SCALEIMAGEVIEW FUNCTIONS

ImageView supports these functions in addition to the Shared View functions.

LoadImageViewBitmap(imageviewname)
Assign the current Bitmap contents to the specified ImageView.

LoadImageView(imageviewname, dir, filename)
Load an image into the specified ImageView using LoadBitmapResize.
The image aspect ratio is maintained and the image is scaled to fit the ImageView.
The gravity of the ImageView is set to CENTER.

LoadImageViewFill(imageviewname, dir, filename)
Load an image into the specified ImageView using LoadBitmapResize.
The image aspect ratio is not maintained and the image is stretched to fill the ImageView.
The gravity of the ImageView is set to CENTER.

SetImageViewGravity(imageviewname, dir, filename)
Set the gravity of the ImageView. imggravity should be one of the Gravity constants.


ScaleImageView supports these functions in addition to the Shared View functions.

GetCenter(scaleimageviewname) As returnvalue
Gets a comma separated string of the X and Y pixel values of the full image point which is at the centre of the view.
This can only be set programatically by SetScaleAndCenter or SetScaleAndCenterPixels.

GetIsReady(scaleimageviewname) As returnvalue
It takes a litle time to load an image.
Gets whether the view Is initialised, has dimensions And will display an image.
Returns True if the view is ready to display an image and accept touch gestures.

GetScale(scaleimageviewname) As returnvalue
Gets the present scale (zoom) level for the displayed image as set by the user.
This can only be programmatically set by SetScaleAndCenter or SetScaleAndCenterPixels.

GetMaxZoom(scaleimageviewname) As returnvalue
Gets the maximum zoom level for the displayed image. The default is 2.0.
The minimum zoom is automatically set to fit the entire image to the view

GetSrcHeight(scaleimageviewname) As returnvalue
Get the original full-size height of the image in pixels.
Note that this does not take any applied rotation into account.

GetSrcWidth(scaleimageviewname) As returnvalue
Get the original full-size width of the image in pixels.
Note that this does not take any applied rotation into account.

LoadScaleImageView(scaleimageviewname, dir, filename)
Load an image from a file saved on the device file system into the view.
This method can display JPG and PNG images of any size.
In order to support huge images without running out of memory, a sub-sampled base layer is first loaded.
Higher resolution tiles are loaded for the visible area as the user zooms in.
This cannot load a file from FileDirAssets as ScaleImageView needs random access to the file while displaying it.
An image file in FileDirAssets must be copied elsewhere to use it with a ScaleImageView.

Recycle(scaleimageviewname)
Releases all resources the view is using and resets the state, nulling any fields that use significant memory.
After you have called this method, the view can be re-used by setting a new image.
Settings are remembered but state (scale and center) is forgotten.

SetMaxZoom(scaleimageviewname, maxzoom)
Sets the maximum zoom level for the displayed image. The default is 2.0.
The minimum zoom is automatically set to fit the entire image to the view

SetPanLimit(scaleimageviewname, panlimit)
Sets the image pan limit to one of the PAN_LIMIT values.
PAN_LIMIT_INSIDE is 1. Don't allow the image to be panned off screen.
As much of the image As possible Is always displayed, centered in the view when it Is smaller.
PAN_LIMIT_OUTSIDE is 2, Allow the image to be panned until it Is just off screen, but no further.
The edge of the image will stop when it is flush with the screen edge.
PAN_LIMIT_CENTER is 3.This is the default
Allow the image to be panned until a corner reaches the center of the screen but no further.
Useful when you need to pan any spot on the image to the exact center of the screen.

SetScaleAndCenter(scaleimageviewname, scale, x, y, duration) As returnvalue
Set the scale (zoom) of the displayed image and center it on the point (x,y).
x And y are width and height factor values of the full image size between 0 and 1.
PanLimit should be set to PAN_LIMIT_CENTER if any point is to be centered.
Duration sets the duration of the transition in milliseconds.
Returns False if the image is not ready and the transition was not made otherwise True.

SetScaleAndCenterPixels(scaleimageviewname, scale, x, y, duration) As returnvalue
Set the scale (zoom) of the displayed image and center it on the point (x,y).
x And y are full image size x And y pixel values.
PanLimit should be set to PAN_LIMIT_CENTER if any point is to be centered.
Duration sets the duration of the transition in milliseconds.
Returns False If the image is not ready and the transition was not made otherwise True.

SourceXYtoViewXY(scaleimageviewname, sourcex, sourcey) As returnvalue
Returns a comma separated string of the X and Y pixel position on the view of the specified point of the full size image.
If the image coordinates are currently off screen, the view coordinates will also be outside the view

ViewXYtoSourceXY(scaleimageviewname, viewx, viewey) As returnvalue
Returns a comma separated string of the X and Y pixel position on the full size image of the specified point of the view.

Contents


LISTVIEW FUNCTIONS

ListView supports these functions in addition to the Shared View and ListView and Spinner functions.

GetLabel(listviewname, labelname)
Makes the ListView.SingleLineLayout.Label accessible as a Label view.
The layout functions of the ListView items may be changed using the label functions.

SetFastScrollEnabled(listviewname, scrollstate)
Sets whether the fast scroll icon will appear when the user scrolls the list. The default Is False.

SetItemHeight(listviewname, itemheight)
Sets the ItemHeight of the SingleLineLayout in a ListView.

SetLayoutBackgroundColor(listviewname, cornerradius, backgroundcolor)
Set the ListView.SingleLineLayout.Background property of the ListView to a ColorDrawable.

SetLayoutBackgroundColorGradient(listviewname, orientation, cornerradius, colorsarrayname) As returnvalue
Set the ListView.SingleLineLayout.Background property of the ListView to a GradientDrawable.
Returns false if less than two colors are in the array or name not found otherwise returns true.
Orientation can be one of the following -
"TOP_BOTTOM", "TR_BL" (Top-Right to Bottom-Left, "RIGHT_LEFT", "BR_TL" (Bottom-Right to Top-Left)
"BOTTOM_TOP", "BL_TR" (Bottom-Left to Top-Right), "LEFT_RIGHT", "TL_BR" (Top-Left to Bottom-Right)

SetScrollColor(listviewname, color)
Sets the background color that will be used while scrolling the ListView.

Contents


LISTVIEW AND SPINNER FUNCTIONS

ListView and Spinner support these functions in addition to the Shared View and ListView and Spinner functions.

AddItem(viewname, item)
Add an item to a ListView or Spinner.

AddAll(viewname, itemsarrayname)
Add an array of items to a ListView or Spinner.

Clear(viewname)
Clears the items from a ListView or Spinner.

GetItemAt(viewname, index) As returnvalue
Returns the item at the specified index from a ListView or Spinner.
In earlier versions this was called GetItem but this conflicts with B4AScript intrinsic GeItem.

GetSize(viewname) As returnvalue
Returns the number of items in a ListView or Spinner.

RemoveAt(viewname, index)
Removes the item at the specified index from a ListView or Spinner.

Contents


PHONE FUNCTIONS

Functions that control certain aspects of the device behaviour.

KeepAlive(isactive, brightscreen)
KeepAlive allows you to prevent the device from turning off the screen.
Once you call KeepAlive(True, ...) the phone screen will stay on till you call KeepAlive(False, ...).
BrightScreen is used with KeepAlive(True, ...) to determine whether to keep the screen bright or dimmed.
It is important to eventually call KeepAlive(False, ...).
The recommended usage is to call KeepAlive(True, ...) in Activity_Resume And call KeepAlive(False, ...) in Activity_Pause.
Note that the user can still turn off the screen by pressing the power button.

PartialLock(isactive)
Calling PartialLock(True) acquires a partial lock on the device.
This will prevent the CPU from going to sleep, even if the user presses the power button.
Make sure to call PartialLock(False) eventually to release this lock.

Shell(command, argsarrayname) As returnvalue
Runs a native shell command. Many commands are inaccessible because of OS security restrictions.
Calling Shell will block the calling thread until the shell process completes.
command - the command To run.
argsarrayname - the name of an array containing additional arguments, pass an empty array if none.
Returns the contents of the StdOut and StdErr streams of the process that ran the command as would be seen in a console.

ShellAsync(command, argsarrayname, callback, params) As returnvalue
Runs a native shell command. Many commands are inaccessible because of OS security restrictions.
Calling Shell will block the calling thread until the shell process completes.
command - the command To run.
argsarrayname - the name of an array containing additional arguments, pass an empty array if none.
callback is the name of the Sub to be called when the shell command completes.
paramsarrayname is the name of an array containing the parameter values to be passed back to the callback function.
Returns stdOut in paramsarrayname(0), stdErr in paramsarrayname(1) and the process exit value in paramsarrayname(2)

Vibrate(milliseconds)
Causes the device to vibrate for the specified number of milliseconds.

Contents


REGULAR EXPRESSION FUNCTIONS

Functions that enable the use of regular expressions.
There is a single Matcher object that can be set by RegexMatcher and RegexMatcher2.
The Matcher can be invoked using the MatcherXxxx functions.

These pattern constants can optionally modify the regular expression match behaviour.
They may be used instead of hard coding numeric values.
These options can be combined by addition.

Regex_CaseInsensitive = 2
Regex_Multiline = 8

RegexIsMatch(pattern, text) As returnvalue
Tests whether the given text is a match for the given pattern and returns a Boolean value.
The whole text should match the pattern. Use RegexMatcher if you are looking for a substring that matches the pattern.
Example: If RegexIsMatch("\d\d\d", EditText1.Text) = False Then ...
The Java code calls Pattern.matcher(Text).matches().

RegexIsMatch2(pattern, options, text) As returnvalue
Same as RegexIsMatch with the additional pattern options.
The Java code calls Pattern.matcher(Text).matches().

RegexMatcher(pattern, text)
Sets the one Matcher object which can then be used to find matches of the given pattern in the text.
Example:
Text = "This is an interesting sentence with two numbers: 123456 and 7890."
Pattern = "\d+" 'one or more digits
RegexMatcher(Pattern, Text)
Do While MatcherFind
  msgbox("Found: " & MatcherMatch)
Loop
The Java code calls Pattern.matcher(Text).

RegexMatcher2(pattern, options, text)
Same as RegexMatcher with the additional pattern options.
The Java code calls Pattern.matcher(Text).

RegexReplace(pattern, text, template) As returnvalue
Replaces all the matches in Text based on the specified Pattern And Template.
Example:
Msgbox(RegexReplace("\d", "1 2 3 4", "-$0-")) '-1- -2- -3- -4-
Returns a new string with the replacements made.
The Java code calls Pattern.matcher(Text).replaceAll(Template).

RegexReplace2(pattern, options, text, template) As returnvalue
Same as RegexReplace with the additional pattern options.
The Java code calls Pattern.matcher(Text).replaceAll(Template).

RegexSplit(arrayname, pattern, text)
Splits the given Text around matches of the Pattern.
Note that trailing empty matches will be removed.
Example:
Dim components() As String
Regex.Split("components", ",", "abc,def,,ghi") : returns: "abc", "def", "", "ghi"
Regex.Split("components, "\|", "abd|def||ghi") : the pipe needs to be escaped as it has special meaning in Regex.
The results will be available in the specified array.
The array does not need to be declared with Dim, if it does not already exist it will be created.
A common mistake is to try to use a reference to the array, arrayname is the name of the array as a String.
The Java code calls Pattern.split(Text).

RegexSplit2(arrayname, pattern, options, text)
Same as RegexSplit with the additional pattern options.
The Java code calls Pattern.split(Text).


The following Matcher functions need to have set a Matcher by invoking RegexMatcher or RegexMatcher2.

MatcherFind As returnvalue
Searches for the next sub-string that matches the pattern. Returns True if a match is found.
The Java code calls Matcher.find().

MatcherGetEnd(index) As returnvalue
Returns the end offset of the specified captured group.
Use MatcherGetEnd(0) to get the end offset of the whole match.
The Java code calls Matcher.end(index).

MatcherGetStart(index) As returnvalue
Returns the start offset of the specified captured group.
Use MatcherGetStart(0) to get the start offset of the whole match.
The Java code calls Matcher.start(index).

MatcherGroup(index) As returnvalue
Returns the value of the specified captured group.
MatcherGroup(0) returns the whole match.
The Java code calls Matcher.group(index).

MatcherGroupCount As returnvalue
Returns the number of capturing groups in the pattern.
Note that the number returned does not include MatcherGroup(0) which is the whole match.
The Java code calls Matcher.groupCount().

MatcherMatch As returnvalue
Returns the matched value. This is the same as calling MatcherGroup(0).
The Java code calls Matcher.group().

Contents


PROGRESSBAR FUNCTIONS

ProgressBar supports these functions in addition to the Shared View functions.

GetIndeterminate(progressbarname) As returnvalue
Returns the current ProgressBar Indeterminate state, True or False.

GetProgress(progressbarname) As returnvalue
Returns the current ProgressBar Progress value between 0 and 100.

SetIndeterminate(progressbarname, indeterminate)
Sets the current ProgressBar Indeterminate state, either True or False.

SetProgress(progressbarname, progress)
Sets the current ProgressBar Progress value. Should be between 0 and 100.

Contents


SCROLLVIEW FUNCTIONS

Scrollviews support these functions in addition to the Shared View functions.
Scrollview functions work on ScrollView, HorizontalScrollView and ScrollView2D.

AdoptPanel(scrollviewname, panelname)
AddPanel is already in use to addd a new Panel view so we called this AdoptPanel instead.
This adds panelname to the internal Panel of the ScrollView resizing the internal Panel to match.
This allows a ScrollView Panel to be laid out in the Designer.

FullScroll(scrollviewname, bottom)
Scrolls the ScrollView to the top or bottom.
True scrolls to the bottom, False scrolls to the top.

GetPanel(scrollviewname, panelname)
Makes the ScrollView Panel accessible as a named Panel View.
The panel is the base ScrollView Panel, not one added by AdoptPanel.
You can add views directly to this Panel or by using SetParent.

GetScrollPosition(scrollviewname) As returnvalue
Returns the current ScrollView ScrollPosition.
For a ScrollView2D this is a comma separated string with the horizontal and then the vertical position.

SetScrollPosition(scrollviewname, position)
Sets the current ScrollView, HorizontalScrollView or ScrollView2D scroll position.
For a ScrollView2D position is a comma separated string with the horizontal and then the vertical position.
For a ScrollView2D if position is a single integer it then sets only the horizontal position.

Contents


SEEKBAR FUNCTIONS

SeekBar supports these functions in addition to the Shared View functions.

GetMax(seekbarname) As returnvalue
Returns the current SeekBar Max value. The default is 100.

GetValue(seekbarname) As returnvalue
Returns the current SeekBar value. The minimum value is always zero.

SetMax(seekbarname, maxvalue)
Sets the current SeekBar Max value. The default is 100.

SetValue(seekbarname, value)
Sets the current SeekBar Value. Should be between 0 and Max.

Contents


SPINNER FUNCTIONS

Spinner supports these functions in addition to the Shared View and ListView and Spinner functions.
Spinner also supports SetTextColor.

GetSelectedIndex(spinnername) As returnvalue
Returns the index of the selected item of a Spinner. Returns -1 if no item is selected.

GetSelectedItem(spinnername) As returnvalue
Returns the the selected item of a Spinner. Returns "" if no item is selected.

SetDropdownBackgroundColor(spinnername, color)
Sets the dropdown background colour.
The color should be set before adding items

SetDropdownTextColor(spinnername, color)
Sets the dropdown text colour.
The color should be set before adding items

SetSelectedIndex(spinnername, index)
Selects the item at the specified index of a Spinner. Pass -1 if no item is selected.

Contents


TABHOST

TabHost supports these functions in addition to the Shared View functions.

AddTab(tabpanelname, tabtitle, tabhostname)
Add a Tab and a new associated Panel to a TabHost.
The tabpanelname may be used to add views to the Tab.

AddTabPanel(tabpanelname, tabtitle, tabhostname)
Add a Tab and an existing Panel, that may already have a layout loaded, to a TabHost.
The tabpanelname may still be used to add more views to the Tab.

GetCurrentTab(tabhostname) As returnvalue
Returns the index of the current tab page.

GetTabCount(tabhostname) As returnvalue
Returns the number of tab pages.

SetCurrentTab(tabhostname, tabnumber)
Selects the current tab page.

Contents


TABLE

Table supports these functions.
Table also supports Left, Right, Top, Bottom, Width, Height and Visible.
These primarily exist so that autoscaling and designer scripts will work on Table as well as regular views.

AddRow(tablename, itemsarrayname)
Add a row of items to a table.

GetCell(tablename, col, row) As returnvalue
Returns the contrents of the cell at col and row in the table.

GetEnableSort(tablename) As returnvalue
Gets whether the table will sort itself when a column header is clicked.
The default for a table is True.

GetHeader(tablename, col) As returnvalue
Returns the contents of the header of col in the table.

GetHeaders(tablename) As returnvalue
Returns the contents of all the headers the table as a comma separated string.

GetNumberOfRows(tablename) As returnvalue
Returns the numbers of rows in tablename.

JumpToRow(tablename, row)
Makes the given row visible by scrolling the table to it..

LoadTableFromCSV(tablename, dir, filename, headersexist) As returnvalue
Clear the previous table and loads the CSV file to the table.
Headersexist should be True if the first line in the CSV contains the header text for the table.
SetHeaderTitles, if needed, and SetColumnWidths need to be called after LoadTableFromCSV as this resets the table to the defaults.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

Refresh(tablename)
Clear the table and re-initialize it empty with the specified number of columns.

ResizeTable(tablename, columns)
Clear the table and re-initialize it empty with the specified number of columns.

RestoreData(tablename) As returnvalue
Restore any saved data for tablename checking that the data exists and that the column count of data and table are equal.
Returns True if the data is restored otherwise False.

SaveData(tablename) As returnvalue
Save the data for tablename in a Process Global so it can be restored when required.
Note that this saves only the data in the rows of the table, not the headers column widths or number of columns.
Nor does it save the sort type of each column. This needs to to be saved separately in some manner.
Returns True if saved otherwise False.

SaveTableToCSV(tablename, dir, filename) As returnvalue
Saves the table to a CSV file.
The saved CSV file will include the column header texts.
Returns an empty string if successful otherwise the exception message of the exception that was raised.

SetEnableSort(tablename, sortstate)
Sets whether the table will sort itself when a column header is clicked.
The default for a table is True.

SetColSortType(tablename, column, sortnumeric)
Sets the type of sort for a column. sortnumeric False is alphabetic, True is numeric.
The default sort type for all columns is alphanumeric.

SetColumnWidths(tablename, widths) As returnvalue
Sets the individual column widths.
Widths is a comma separated string of the widths of each column inpixels and should be scaled from dips using g_scale.
Returns False if the number of header items is not the same as number of columns otherwise returns True.

SetHeaders(tablename, headers) As returnvalue
Sets the text of the headers in the table.
Headers is a comma separated string of the text of each header.
Returns False if the number of header items is not the same as number of columns otherwise returns True.

Contents


TEXTVIEW FUNCTIONS

Views containing text support these functions in addition to the Shared View functions.

CreateTypeface(typeface, style)
There is one Typeface but it can be reinitialised as required.
The Typeface constants below may be used, or use the following case-insensitive values.
Typeface - "Default", "Monospace", "Serif", "Sans_Serif"
Style - 0 Normal : 1 Bold : 2 Italic : 3 Bold_Italic

GetText(viewname) As returnvalue
Get the Text property, if any, of the named view.
For a ToggleButton will return the text appropriate for the state of the button.

SetGravity(viewname, gravity)
Set the Gravity property, if any, of the named view.
The Gravity constants may be used'
Gravity_None, Gravity_Top, Gravity_Bottom, Gravity_Left, Gravity_Right, Gravity_Center
Gravity_CenterHorizontal or Gravity_HCenter, Gravity_CenterVertical or Gravity_VCenter, Gravity_Fill
or use the following numeric values.
NO_GRAVITY = 0; TOP = 48 (0x30) ; BOTTOM = 80 (0x50; LEFT = 3; RIGHT = 5; CENTER = 17 (0x11)
CENTER_HORIZONTAL = 1; CENTER_VERTICAL = 16 (0x10) ; FILL = 119 (0x77)

SetText(viewname, text)
Set the Text property, if any, of the named view.
Although this will set the displayed text of a ToggleButton when the state changes
the text set by SetTextOff/On appropriate to the state of the button will be displayed.

SetTextColor(viewname, color)
Set the TextColor property, if any, of the named view.
This works for Label, Buttons etc. as well as Spinner

SetTextSize(viewname, size)
Set the TextSize property, if any, of the named view.
This works for Label, Buttons etc. as well as Spinner

SetTypeface(viewname)
Set the Typeface property, if any, of the named view to the current typeface.

Contents


TIMER FUNCTIONS

There is one timer and the Timer Tick events are vectored to "Sub timer_tick".

SetTimerEnabled(enabled)
Enable or disable the Timer.
The Timer is automatically disabled on activity pause and, if it was running when paused, re-enabled on activity resume.

SetTimerInterval(interval)
Set the timer interval in milliseconds.

Contents


USER INTERACTION FUNCTIONS

These functions are implemented using modal dialogs.
While the dialogs are shown only messages that draw the UI are processed.
Most other events cannot be raised while a modal dialog is shown.
The use of modal dialogs may cause exceptions in some circumstances.
Their use is deprecated for all but the most trivial programs where exceptions would merely be an annoyance.
See the description under Async Functions for the later Async implementation of dialogs which avoids modality.

Many dialogs offer a choice of three buttons whose text can be customised.
  positive - The text to show For the "positive" button. Pass "" to hide the button.
  cancel - The text to show For the "cancel" button. Pass "" to hide the button.
  negative - The text to show For the "negative" button. Pass "" to hide the button.

CallDoEvents
Allow the message loop to run, lets views repaint themselves.

Dialog reponse codes
These values returned from dialogs indicate the user's response.

DialogResponse_Positive
DialogResponse_Cancel
DialogResponse_Negative

These dialogs allow interaction with the user.

GetInput As returnvalue
Get the user input from the latest InputBox, InputDate or InputTime modal dialog.

InputBox(prompt, title, positive, cancel, negative, inputtype) As returnvalue
Show a modal dialog box and prompt the user for data.
prompt is displayed below the title and can be used to give a hint to the user.
title is displayed at the top of the dialog.
inputtype sets the value of the InputBox InputType property and must be one of the InputBox type codes
Returns a DialogResponse value with the input text available by calling GetInput.

InputBox InputType codes

Type_Decimal - Signed decimal value including a decimal point
Type_Integer - Unsigned integer value
Type_SignedInteger - Signed integer value
Type_Phone - Any characters valid in a US phone number
Type_Text - Normal text- the default

InputCustom(viewname, title, positive, cancel, negative) As returnvalue
Allows a custom dialog to be presented to the user.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
viewname - the name of a single view to display in the dialog, most probably a panel
title - the text in the dialog's title bar.
Returns a DialogResponse value.
Example:
REM first add your panel.
AddPanel("mypanel", 0, 0, pwidth, pheight, "")
REM change the panel background colour if required
SetColor("mypanel", 0, cLightGray)
REM next, add all the desired views to the panel like this
AddLabel("mylabel", 0, 0, 60 * g_scale, 30 * g_scale, "mypanel")
SetText("mylabel", "label text")
REM now remove the panel from the activity
RemoveView("mypanel")
REM now call InputCustom
sel = InputCustom("mypanel","A Title", "Yes", "Cancel", "No")

InputDate(prompt, title, startdateticks, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for a date.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
InputDate will not display correctly in landscape mode on most devices.
In this case InputDate2 can be used instead.
Returns a DialogResponse value with the input value avalable to GetInput as a ticks value.

InputDate2(title, startyear, endyear, showdate, showmonth, showyear, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for a date.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Day and month numbers start at 1.
This is simplistic allowing 31 days every month as we can't manipulate a modal dialog once it is shown.
This does a rough check for validity, suffixing the GetInput value with "?" if the day number is too big for the month
Returns a DialogResponse value with the 'dd/MM/yyyy' value available to GetInput as a string

InputFile(filepath, filename, filefilter, title, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for a path or file name.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Returns a DialogResponse value with the input values available to GetInput as a comma separated string.
The first part is the file path and the last part is file name. If the user selected a path the file name is an empty string.

InputListBox(itemarrayname, title, selecteditem) As returnvalue
Show a modal dialog box and prompt the user to select an item.
selecteditem is the index of the item that will first be selected or -1 if no item should be preselected.
Returns the index of the selected item or DialogResponse_Cancel if the user pressed on the back key.

InputMultiListBox(itemarrayname, title) As returnvalue
Show a modal dialog box and prompt the user to select one or more items.
Returns a comma separated list of indices selected that may be separated with StrSplit.
Returns an empty string ("") if the Back button was pressed or no items were selected.

InputNumber(showsign, digits, number, title, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for an integer number.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
If ShowSign is True the sign of the number corresponds to the sign entered by the user.
Returns a DialogResponse value with the input number available to GetInput.

InputTime(prompt, title, starttimeticks, as24hours, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for a time.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Due to an Android bug InputTime will not display correctly in landscape mode on most devices.
In this case InputTime2 can be used instead.
Returns a DialogResponse value with the input value available to GetInput as a ticks value.

InputTime2(prompt, title, showhour, showminute, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user for a time. The time is always in 24 hour format.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Returns a DialogResponse value with the time available to GetInput as a string formatted as 'HH:mm'.
The literal string result avoids issues with Daylight Saving Time if ticks were used and Time used to parse it.
InputTime appears to massage its ticks value to suit the present DST setting so Time can be used to parse its return.

MessageBox(message, title, positive, cancel, negative) As returnvalue
Show a modal dialog box and prompt the user to make a selection.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Returns a DialogResponse value.

ProgressHide
Hide a non-modal progress dialog.

ProgressShow(text, usercancel)
Show a non-modal progress dialog.
Shows a dialog with a circular spinning bar and the specified text.
Unlike Msgbox And InputList methods, the code will not block.
You should call ProgressDialogHide to remove the dialog.
If usercancel is True The dialog will also be removed If the user presses on the Back key.

ShowToast(message, longduration)
Shows a toast message. Setting longduration to true will cause the toast message to stay on the screen longer.

Contents


ASYNC USER INTERACTION FUNCTIONS

These functions expose non-modal equivalents to the modal dialogs as well as the asynchronous Sleep.

In later versions of B4A DoEvents and modal dialogs are deprecated and Sleep and non-modal dialogs are recommended.
DoEvents shares the same low level mechanism as the modal dialogs implementation.
This modality mechanism can lead to stability issues with later versions of Android which have more complex message processing.
The purpose of the modality mechanism was to allow the UI to be updated while the Main thread is busy.
It accesses the process message queue and runs some of the waiting messages.
As Android evolved, the handling of the message queue became more sophisticated and fragile.
The reasons for deprecating DoEvents and modal dialogs (such as Msgbox And InputList) are:
  1. It is a major source of instability issues. It can lead to hard to debug crashes or ANR (Application Not Responding) dialogs.
  2. There are better ways to keep the Main thread free. For example use the asynchronous SQL methods instead of the synchronous methods.
  3. It doesn't do what many developers expect it to do as it only handles UI related messages. Most events are not be raised from a modal call.
It is now possible to call Sleep or an async dialog to pause the current sub and resume it after the waiting messages are processed.
The non-modal mechansim is completely different from the modality mechanism.
It doesn't block the thread and pump only some messages, instead it preserves the sub state and returns to the message loop.
Unlike the modal mechanism with non-modality all messages will be processed and other events will be raised.
With that said, DoEvents and modal dialogs are still there and existing applications will work exactly as before but may have problems.

All the Async functions below return immediately to the calling Sub having set up the sleep or dialog to be run by the messsage loop.
Unlike in B4A further program statements can follow the Async call and will be immediately executed.
Once the calling Sub, and any in a call chain that invoked it, returns the message loop will then process the sleep or dialog.
When the sleep time has elapsed or the dialog is closed then the message loop will invoke the callback Sub with the specified parameters.
If the callback does not exist then no error is raised.
It can be occasionally useful to pass, say, an empty string when a callback is not required.

The Async functions parameter lists are an extension of those of their modal counterparts.
Each function usually has three extra parameters, MsgboxAsync has two.
  cancellable - if True then the dialog can be cancelled by clicking on the back key or outside the dialog.
  callback - the name of the Sub to be called when the dialog is dismissed or the sleep expires.
  paramsarrayname - the name of an array containing the parameter values to be passed to the callback function.
Where an input value is available by GetInput from a modal dialog it is also available to the non-modal counterpart.

Many dialogs offer a choice of three buttons whose text can be customised.
  positive - the text to show For the "positive" button. Pass "" to hide the button.
  cancel - the text to show For the "cancel" button. Pass "" to hide the button.
  negative - the text to show For the "negative" button. Pass "" to hide the button.

The examples in asynctest.b4s in the BasicIDE Script folder show how asynchronous dialogs and sleep can be implemented.
You may need to keep what would be local values in global variables or arrays as local variable values will be lost.
The paramsarrayname parameter array may be used to hold local values that will be returned to the callback Sub.
The paramsarrayname array should be declared with the same number of elements as there are parameters in the callback Sub.
On occasion parameter array item at index 0 will be overwritten to pass a DialogResponse value to the callback Sub.
As there may be more than one outstanding callback at any one time care should be taken when reusing a parametername array.

AsyncInputBox(prompt, title, positive, cancel, negative, inputtype, cancellable, callback, paramsarrayname)
Show a modal dialog box and prompt the user for data.
prompt is displayed below the title and can be used to give a hint to the user.
title is displayed at the top of the dialog.
inputtype sets the value of the InputBox InputType property and must be one of the InputBox type codes
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.

Type_Decimal - Signed decimal value including a decimal point
Type_Integer - Unsigned integer value
Type_SignedInteger - Signed integer value
Type_Phone - Any characters valid in a US phone number
Type_Text - Normal text- the default

AsyncInputCustom(viewname, title, positive, cancel, negative, cancellable, callback, paramsarrayname)
Show a non-modal custom dialog.
viewname, probably a Panel though there is no check for this, is the name of the view to be displayed by the custom dialog.
title is displayed at the top of the dialog.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
Returns a DialogResponse value to the callback function in paramsarrayname(0)
Other results can be retrieved from the views on the displayed Panel
Example:
REM first add your panel.
AddPanel("mypanel", 0, 0, pwidth, pheight, "")
REM change the panel background colour if required
SetColor("mypanel", 0, cLightGray)
REM next, add all the desired views to the panel like this
AddLabel("mylabel", 0, 0, 60 * g_scale, 30 * g_scale, "mypanel")
SetText("mylabel", "label text")
REM now remove the panel from the activity
RemoveView("mypanel")
REM now call InputCustom
Dim param(1)
AsyncInputCustom('mypanel', 'The Title' 'Yes', 'Cancel', 'No', True, 'callbacksubname', 'param')

AsyncInputDate2(title, startyear, endyear, showdate, showmonth, showyear, positive, cancel, negative, cancellable, callback, paramsarrayname)
Show a non-modal dialog box and prompt the user for a date.
title is displayed at the top of the dialog.
startyear and endyear determine the available year range.
showdate, showmonth and showyear specify the date selected when the dialog is shown.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
Day and month numbers start at 1.
Returns a DialogResponse value in paramsarrayname(0) with the 'dd/MM/yyyy' value available to GetInput as a string
The advantage of this over the modal InputDate2 is that the number of days are dynamically adjusted according to the selected month and year.

AsyncInputFile(filepath, filename, filefilter, title, positive, cancel, negative, cancellable, callback, paramsarrayname)
Show a modal dialog box and prompt the user for a path or file name.
title is displayed at the top of the dialog.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
Gets or sets the filter values of the dialog.
The filter can be a single value ".txt" or a comma separated list of values ".jpg,.png".
Note that spaces in filter values are significant and are not ignored.
If a filename contains the text of a filter value the File will be displayed.
A value of an empty string, the default, will show all files.
Returns a DialogResponse value in Params(0) with the input values available to GetInput as a comma separated string.
The first part is the file path and the last part is file name. If the user selected a path the file name is an empty string.

AsyncInputListBox(itemarrayname, title, selecteditem, cancellable, callback, paramsarrayname)
Show a modal dialog box and prompt the user to select an item.
itemarrayname is the name of an array containing the items to display.
title is displayed at the top of the dialog.
selecteditem is the index of the item that will first be selected or -1 if no item should be preselected.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Returns the index of the selected item in Params(0) or DialogResponse_Cancel if the user pressed on the back key.

AsyncInputMultiMapBox(keysarrayname, valuesarrayname, title, cancellable, callback, paramsarrayname)
Show a non-modal dialog with a list of items and checkboxes. The user can select multiple items.
This is the non-modal replacement for the modal MultiListBox.
title is displayed at the top of the dialog.
keysarrayname is an array of items to display.
valuesarrayname is an array of the state, True or False, of the checkbox for each item.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
Sets valuesarrayname to show the state, True or False, of the checkboxes selected by the user.
Returns the number of selected items in Params(0).
The dialog is closed by pressing on the "Ok" button.

AsyncInputNumber(showsign, digits, number, title, positive, cancel, negative, cancellable, callback, paramsarraynam)
Show a modal dialog box and prompt the user for an integer number.
title is displayed at the top of the dialog.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
showsign if True makes the sign of the number correspond to the sign entered by the user.
Returns a DialogResponse value in Params(0) with the input number available to GetInput.

AsyncInputTime2(title, showhour, showminute, positive, cancel, negative, cancellable, callback, paramsarrayname)
Show a non-modal dialog box and prompt the user for a time. The time is always in 24 hour format.
title is displayed at the top of the dialog.
showhour and showminute specify the time selected when the dialog is shown.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
Returns a DialogResponse value in paramsarrayname(0) with the time available to GetInput as a string formatted as 'HH:mm'.
The literal string result avoids issues with Daylight Saving Time if ticks were used and Time used to parse it.
InputTime appears to massage its ticks value to suit the present DST setting so Time can be used to parse its return.

AsyncMsgbox(msg, title, callback, paramsarrayname)
Show a non-modal message box with the specified message and title.
The dialog will show one OK button.
message is the dialog message.
title is the dialog title.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
AsyncMsgbox does not return a DialogResponse value.

AsyncMsgbox2(msg, title, positive, cancel, negative, cancellable, callback, paramsarrayname)
Show a non-modal message box with the specified message and title.
message is the dialog message.
title is the dialog title.
Set the positive, cancel and negative parameters to the desired button text or leave blank to omit the button.
The cancellable, callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.
Returns a DialogResponse value in paramsarrayname(0).

AsyncSleep(delay, callback, paramsarrayname)
Invoke the callback after the specified time has elapsed.
delay is the length of time to sleep in milliseconds.
The callback and paramsarrayname parameters are as described in the ASYNC USER INTERACTION introduction above.

Contents


DEBUGGING FUNCTIONS

The BreakXxxx functions below rely on a modal dialog to halt program execution while debugging.
At the moment these are available and for their use here cause no problems.
However if modality problems are experienced DebugSnapShot, AsyncMsgbox and AsyncMsgbox2 are alternatives.

Blog(message)
Logs the provided message to the B4A IDE Log window.
The project must be running in Debug mode in the B4A IDE or with
'#BridgeLogger: True' in the Main module and running in Release mode in the B4A IDE.

Break
Halt the program and display the local and global variable values and any Print output.
This is the same as setting the break line to the line following this statement.
Only one breakpoint can be active at any one time so this overwrites any Break set by BreakAt.

BreakAt(linenumber)
Halt the program before executing the specified line and display the local and global variable values and any Print output.
This is the same as setting the break line to the line number specified.
Only one breakpoint can be active at any one time.
A breakpoint set by BreakAt can be disabled by invoking BreakAt(0).

BreakAndPrint(message)
Halt the program and display the local and global variable values and any Print output.
This is the same as calling Break except that message is added to the Print output as though Printed.

BreakAndPrintIf(break, message)
Halt the program and display the local and global variable values and any Print output if boolbreak is True.
This is the same as calling BreakIf except that message is added to the Print output as though Printed if lbreak is True.

BreakIf(break)
Halt the program and display the local and global variable values and any Print output if boolbreak is True.
This is the same as setting the break line to the line following this statement if break is True otherwise it is set to 0.
Only one breakpoint can be active at any one time so this overwrites any Break set by BreakAt.

DebugSnapShot(message, showglobals)
Display the local, and optionally global, variable values and any Print output in a non-modal dialog.
If showglobals is false then global variables are not included, this can be useful if there are many globals.
message will be prepended to the variable and Print data.
Unlike the BreakXxxx functions this is not a modal display and is provided for use if modality problems are experienced.
The program will carry on running while the dialog is displayed.
The non-modal AsyncMsgbox and AsyncMsgbox2 can also be used for displaying debug data if modality problems are experienced.

Contents


COLOR NAMES AND CONSTANTS

These additional color constants return the color codes for the named color.

cDarkGray
cLightGray
cMagenta
cTransparent

GetColourName(colourvalue)
Returns the properly cased HTML or X11 name for a colour from its value.
colourvalue is the integer value of the colour.
The alpha value of colourvalue is ignored.
Returns an empty string if colourvalue does not match a named colour.

GetColourNameAt(index)
Returns the properly cased HTML or X11 name for a colour at index position in the list of colours.
The colour names are in alphabetical order.
This function can be used with GetColourNumbers to iterate through all the supported colour names.

GetnumberOfColours
Returns the number of colours in the list of colours.

GetNamedColour(name, alpha)
Returns the signed integer representing a colour from its HTML or X11 name.
name is the name of the required colour.
alpha specifies the Alpha value of the returned colour value.
Returns Black with the specified alpha value if the colour name does not exist.

Contents


KEYCODE FUNCTIONS AND CONSTANTS

Pass the KeyCode value from the Activity_KeyPress event to any of these functions
They will Return True or False depending upon whether the passed KeyCode is contained within that particular set.

Key_isNumber(KeyCode)
Numeric keys are: 0123456789

Key_isAlpha(KeyCode)
 Alpha keys are: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Key_isSymbol(KeyCode)
 Symbol keys are: '@/,=(-.+#^);\*

Key_isKeyboard(KeyCode)
Keyboard keys are: AltLeft AltRight Clear Del Enter Num ShiftLeft ShiftRight Space Symbol

Key_isDPad(KeyCode)
DPad Keys are: Left Center Right Up Down

Key_isMedia(KeyCode)
Media keys are: FastForward Next Play/Pause Rewind Stop Mute

Key_isDevice(KeyCode)
Device keys are : Back Call Camera EndCall Envelope Explorer Focus Grave HeadsetHook Home
       Menu Notification Search SoftLeft SoftRight VolumeUp VolumeDown


Pass a KeyCode to these functions to get the ASCII value of a key as returned by Asc().
Whether a KeyCode is a letter, number or symbol can be checked using the KeyCode functions above.
KeyCodes for 0 to 9 are integer values 7 to 16.
KeyCodes for letters A to Z are integer values 29 to 54.

KeyToAsciiUpper(KeyCode)
KeyToAsciiLower(KeyCode)
KeyToNumberKey(KeyCode)


KeyCode constants:
Note that not all KeyCode constants are supported.
Whether a KeyCode is a letter, number or symbol can be checked using the KeyCode functions above.
KeyCodes for 0 to 9 are integer values 7 to 16.
KeyCodes for letters A to Z are integer values 29 to 54.

Key_AltLeft
Key_AltRight
Key_Back
Key_Call
Key_Camera
Key_Clear
Key_Del
Key_DPadCenter
Key_DPadDown
Key_DPadLeft
Key_DPadRight
Key_DPadUp
Key_EndCall
Key_Enter
Key_Envelope
Key_Explorer
Key_Focus
Key_Grave
Key_HeadSetHook
Key_Home
Key_MediaFastForward
Key_MediaNext
Key_MediaPlayPause
Key_MediaPrevious
Key_MediaRewind
Key_MediaStop
Key_Menu
Key_Mute
Key_Notification
Key_Num
Key_Search
Key_ShiftLeft
Key_ShiftRight
Key_SoftLeft
Key_SoftRight
Key_Sym
Key_Tab
Key_Unknown
Key_VolumeDown
Key_VolumnUp

Contents


GRAVITY CONSTANTS

These gravity constants return gravity values needed by functions for justifying text and images.
They may be used instead of hard coding numeric values.

Gravity_None
Gravity_Top
Gravity_Bottom
Gravity_Left
Gravity_Right
Gravity_Center
Gravity_CenterHorizontal
(also Gravity_HCenter)
Gravity_CenterVertical
(also Gravity_VCenter)
Gravity_Fill

Contents


TYPEFACE CONSTANTS

These typeface constants return the values needed for the typeface functions.
They may be used instead of hard coding numeric values.

FontDefault
FontMonospace
FontSerif
FontSansSerif
StyleNormal
StyleBold
StyleItalic
StyleBoldItalic

Contents


SENSOR CONSTANTS

These sensor constants return the integer identifiers needed for the different sensor types.
They may be used instead of hard coding numeric values.

cAccelerometer = 1
cMagnetic = 2
cOrientation = 3
cGyroscope = 4
cLight = 5
cPressure = 6
cTemperature = 7
cProximity = 8
cGravity = 9

Here are some values for less common sensors that might be present
cLinearAcceleration = 10
cRotationVector = 11
cRelativeHumidity = 12
cAmbientTemperature = 13
cMagneticFieldUncalibrated = 14
cGameRotationVector = 15
cGyroscopeUncalibrated = 16
cSignificantMotion = 17
cStepDetector = 18
cStepCounter = 19
cGeoMagneticRotationVector = 20
cHeartRate = 21
cStationaryDetect = 29
cMotionDetect = 30
cHeartBeat = 31
cLowLatencyOffbodyDetect = 34
cAccelerometerUncalibrated = 35

Contents