Beginners guide
Upcoming SlideShare
Loading in...5
×
 

Beginners guide

on

  • 14,753 views

Basic4android is a powerful yet simple IDE / programming language for Android development. Basic4android language is similar to Visual Basic. Basic4android includes a powerful visual designer.

Basic4android is a powerful yet simple IDE / programming language for Android development. Basic4android language is similar to Visual Basic. Basic4android includes a powerful visual designer.
All the main features of Android are supported including:
SQL databases, GPS, Serial ports (Bluetooth), Camera, XML parsing, Web services (HTTP),
Services (background tasks), JSON, Animations, Network (TCP and UDP), Text To Speech (TTS), Voice Recognition, WebView, AdMob (ads), Charts, OpenGL, Graphics and more.

Statistics

Views

Total Views
14,753
Views on SlideShare
14,745
Embed Views
8

Actions

Likes
3
Downloads
1,054
Comments
1

5 Embeds 8

http://www.slashdocs.com 3
http://www.linkedin.com 2
http://www.slideshare.net 1
http://twitter.com 1
http://translate.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • nice..tnx
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Beginners guide Beginners guide Document Transcript

    • Beginners GuideCopyright: © 2011 Anywhere Software Edit 1.1
    • Beginners Guide 2 Basic4Android1 Getting started ......................................................................................................................... 5 1.1 Installing Basic4Android and Android SDK .................................................................... 5 1.1.1 Install and configure Basic4Android ........................................................................ 7 1.2 Installing Android Emulator............................................................................................. 82 My first program (MyFirstProgram.b4a)............................................................................... 123 Second program (SecondProgram.b4a) ................................................................................. 304 The IDE ................................................................................................................................ 43 4.1 Menu and Toolbar.......................................................................................................... 44 4.1.1 Toolbar .................................................................................................................. 44 4.1.2 File menu ............................................................................................................... 45 4.1.3 Edit menu............................................................................................................... 45 4.1.4 Project menu .......................................................................................................... 46 4.1.5 Tools menu ............................................................................................................ 47 4.2 Code area....................................................................................................................... 48 4.2.1 Undo – Redo ............................................................................................. 48 4.2.2 Collapse a subroutine ............................................................................................. 48 4.2.3 Collapse the whole code......................................................................................... 49 4.2.4 Commenting and uncommenting code ...................................................... 50 4.2.5 Bookmarks .................................................................................. 50 4.2.6 Indentation ............................................................................................... 51 4.2.7 Autocomplete ................................................................................................. 53 4.2.8 Debugging ............................................................................................................. 55 4.2.9 Breakpoints............................................................................................................ 57 4.3 Tabs............................................................................................................................... 60 4.3.1 Module and subroutine lists ............................................................... 60 4.3.2 Files ....................................................................................................... 61 4.3.3 Logs ...................................................................................................... 62 4.3.4 Libs ........................................................................................................ 635 Screen sizes and resolutions................................................................................................... 646 The Emulator......................................................................................................................... 69 6.1 Launch an Emulator....................................................................................................... 69 6.2 Generate a new Emulator............................................................................................... 71 6.3 Emulator problems......................................................................................................... 737 B4A Bridge ........................................................................................................................... 748 The Designer ......................................................................................................................... 77 8.1 The menu....................................................................................................................... 78 8.1.1 File menu ............................................................................................................... 78 8.1.2 AddView menu ...................................................................................................... 78 8.1.3 The Tools menu ..................................................................................................... 79 8.2 Tools ............................................................................................................................. 80 8.2.1 Generate Members ................................................................................................. 80 8.2.2 BringTo Front ........................................................................................................ 81 8.2.3 Duplicate Selected View ........................................................................................ 81 8.2.4 Remove Selected View .......................................................................................... 82 8.2.5 Change grid............................................................................................................ 82 8.2.6 Connect device or emulator.................................................................................... 83 8.3 General settings ............................................................................................................. 83 8.4 Image files ..................................................................................................................... 84 8.5 Parameter list ................................................................................................................. 85
    • Basic4Android 3 Beginners guide 8.6 Layout variants .............................................................................................................. 879 Process and Activity life cycle............................................................................................... 9210 Variables and objects......................................................................................................... 96 10.1 Variable Types............................................................................................................... 96 10.2 Names of variables ........................................................................................................ 97 10.3 Declaring variables ........................................................................................................ 97 10.3.1 Simple variables..................................................................................................... 97 10.3.2 Array variables....................................................................................................... 98 10.3.3 Type variables...................................................................................................... 100 10.4 Casting ........................................................................................................................ 101 10.5 Scope........................................................................................................................... 102 10.5.1 Process variables.................................................................................................. 102 10.5.2 Activity variables ................................................................................................. 102 10.5.3 Local variables..................................................................................................... 102 10.6 Tips ............................................................................................................................. 10311 Modules........................................................................................................................... 10412 Example programs........................................................................................................... 105 12.1 User interfaces ............................................................................................................. 105 12.1.1 Menu example (UserInterfaceMenu.b4a)............................................................. 106 12.1.2 TabHost example (UserInterfaceTabHost.b4a) ................................................... 107 12.1.3 Button toolbox example (UserInterfaceButtonToolbox.b4a)................................ 108 12.2 Program with 3 Activities (ThreeActivityExample.b4a) .............................................. 109 12.3 ScrollView example..................................................................................................... 116 12.4 Data base example ....................................................................................................... 11713 Basic language................................................................................................................. 118 13.1 Program flow ............................................................................................................... 118 13.1.1 Prorogress_Globals routine .................................................................................. 118 13.1.2 Globals routine..................................................................................................... 119 13.1.3 Activity_Create (FirstTime As Boolean) routine .................................................. 119 13.1.4 Activity_Resume routine...................................................................................... 119 13.1.5 Activity_Pause (UserClosed As Boolean) routine................................................. 119 13.2 Expressions.................................................................................................................. 121 13.2.1 Mathematical expressions .................................................................................... 121 13.2.2 Relational expressions.......................................................................................... 122 13.2.3 Boolean expressions............................................................................................. 122 13.3 Conditional statements................................................................................................. 122 13.3.1 If – Then – End If................................................................................................. 123 13.3.2 Select – Case........................................................................................................ 124 13.4 Loop structures ............................................................................................................ 126 13.4.1 For – Next............................................................................................................ 126 13.4.2 Do - Loop ............................................................................................................ 127 13.5 Subs............................................................................................................................. 128 13.5.1 Declaring ............................................................................................................. 128 13.5.2 Calling a Sub........................................................................................................ 128 13.5.3 Naming ................................................................................................................ 128 13.5.4 Parameters ........................................................................................................... 129 13.5.5 Returned value ..................................................................................................... 129 13.6 Libraries ...................................................................................................................... 130 13.6.1 Standard libraries ................................................................................................. 130 13.6.2 Additional libraries folder .................................................................................... 130 13.6.3 Error message "Are you missing a library reference?" .......................................... 13114 B4A Keywords ................................................................................................................ 133 14.1 Bit ............................................................................................................................... 133
    • Beginners Guide 4 Basic4Android 14.2 DateTime..................................................................................................................... 134 14.3 Exception..................................................................................................................... 137 14.4 Keywords .................................................................................................................... 138 14.5 LayoutValues............................................................................................................... 150 14.6 String........................................................................................................................... 151 14.7 StringBuilder ............................................................................................................... 153 14.8 Timer........................................................................................................................... 15515 Views .............................................................................................................................. 157 15.1 Activity........................................................................................................................ 157 15.2 Button.......................................................................................................................... 161 15.3 CheckBox.................................................................................................................... 164 15.4 EditText....................................................................................................................... 167 15.5 ImageView .................................................................................................................. 172 15.6 Label ........................................................................................................................... 175 15.7 ListView...................................................................................................................... 178 15.8 Panel............................................................................................................................ 183 15.9 ProgressBar ................................................................................................................. 186 15.10 RadioButton............................................................................................................. 188 15.11 ScrollView............................................................................................................... 191 15.12 SeekBar ................................................................................................................... 194 15.13 Spinner .................................................................................................................... 197 15.14 TabHost ................................................................................................................... 201 15.15 ToggleButton........................................................................................................... 205 15.16 View ........................................................................................................................ 208 15.17 WebView................................................................................................................. 21016 Graphics .......................................................................................................................... 21417 VB6 versus B4A.............................................................................................................. 21518 Glossary .......................................................................................................................... 220Contributors:Erel UzielKlaus Christlnfordbscndrd
    • Basic4Android 5 Beginners guide1 Getting startedBasic4android is a simple yet powerful development environment that targets Android devices.Basic4android language is similar to Visual Basic language with additional support for objects.Basic4android compiled applications are native Android applications, there are no extra runtimes ordependencies.Unlike other IDEs Basic4android is 100% focused on Android development.Basic4android includes a powerful GUI designer with built-in support for multiple screens andorientations. No XML writing is required.You can develop and debug with the Android emulator or with a real device(USB connected or over the local network).Basic4android has a rich set of libraries that make it easy to develop advanced applications.This includes: SQL databases, GPS, Serial ports (Bluetooth), Camera, XML parsing, Web services(HTTP), Services (background tasks), JSON, Animations, Network (TCP and UDP), Text To Speech(TTS), Voice Recognition, WebView, AdMob (ads), Charts, OpenGL, Graphics and more.Android 1.6 and above are supported (including tablets like Motorola Xoom).1.1 Installing Basic4Android and Android SDKBasic4android depends on two additional (free) components:- Java JDK- Android SDKInstallation instructions:The first step should be to install the Java JDK as Android SDK requires it as well.Note that there is no problem with having several versions of Java installed on the same computer.- Open the Java 6 JDK download link.- Select "Windows" in the platform combo box (for 64 bit machines as well).Android SDK doesnt work with Java 64bit JDK.You should install the regular JDK for 64-bit computers as well.- Press on the red Continue button. There is no need to sign in!If for some reason, you dont see the red Continue button try to switch to a different browser.- On the next page, you should press on the file link:- Download the file and install it.
    • Beginners Guide 6 Basic4AndroidNext step is to install the Android SDK and a platform- Download Android SDK.- Install the SDK.- When the application opens, it will show a page with all the available packages. Press the"Cancel" button, as you do not need to install all the platforms.- Choose "Available Packages" and choose "SDK Platform 2.2, API 8". It should appear under the"Android repository" node.The file structure of API 9 is different. For now, you should use API 8.Note that you can install more packages later.- Press on Install Selected and install both packages.
    • Basic4Android 7 Beginners guide1.1.1 Install and configure Basic4Android- Download and install Basic4android.- Open Basic4android.- Choose Tools menu - Configure Paths.- Use the browse buttons to locate "javac.exe" and "android.jar"javac is located under <java folder>bin.android.jar is located under <android-sdk-windows>platformsandroid-8On Windows 64 bit, Java will probably be installed under C:Program Files (x86).
    • Beginners Guide 8 Basic4Android1.2 Installing Android EmulatorPlease follow the installation (and configuration) instructions if you have not done it yet:http://www.basic4ppc.com/forum/basic...droid-sdk.html.In this chapter, we will create a new AVD (Android Virtual Device) which is an emulator instance.Then we will create a simple program that displays a simple message box and writes a message tothe log.You can also connect a real device to the IDE:Connecting your device with ADBConnecting your device with B4A-BridgeCreate new AVD- Run Basic4android.- Choose Tools Menu - Run AVD Manager. Wait a few seconds.- The AVD Manager should appear:- Choose New and fill the fields similar to the following image:
    • Basic4Android 9 Beginners guide- Press on Create AVD.- Note that you can create more than one AVD. Each can have a different resolution or can target adifferent API version (you will need to install additional platforms first).- Now, press Start in order to start the emulator
    • Beginners Guide 10 Basic4Android- You will see several windows popping up and disappearing. This is fine.- The emulator should boot up:Wait... on the first time it can take several minutes until the emulator is ready.The emulator is ready when it gets to this screen:
    • Basic4Android 11 Beginners guideYou may see this screen, which is the lock screen, instead: Drag the lock icon to the right to unlock the device. Note that there is no need to restart the emulator each time you deploy a program. The emulator can be kept running all the time. If you are not familiar with Android you can play with the emulator. Press on the button with the small squares to get to the application page.
    • Beginners Guide 12 Basic4Android2 My first program (MyFirstProgram.b4a)Let us write our first program.The suggested program is a math trainer for kids.On the screen, we will have:- 2 Labels displaying randomly generated numbers- 1 Label with the math sign- 1 EditText view where the user must enter the result- 1 Button, used to either confirm when the user has finished entering the result or generate a newcalculation.- 1 Label with a comment about the result.We will design the layout of the user interface with the Designer on the Emulator and go step bystep through the whole process.
    • Basic4Android 13 Beginners guideRun the IDESave the project.You must save the project before you can run the Designer. Create a new folder MyFirstProgram and save the project with the name MyFirstProgram.Run the Emulator.Select the Emulator.
    • Beginners Guide 14 Basic4AndroidThe portrait Emulator in this case. Click on Click onWait until the Emulator is ready, this will take quite some time.Run the Designer. Wait until the Designer is ready.
    • Basic4Android 15 Beginners guide Connect the Emulator to the Designer. Wait until the Designer and the Emulator are connected, this can take some time, be patient. You will see the state of the Designer here:The top of the Emulator will have this look.
    • Beginners Guide 16 Basic4AndroidNow we will add the 2 Labels for the numbers.In the Designer add a Label.The label appears in the Emulator, and its default parameters are listed in the Designer. Resize and move the Label with the red squares like this. The new parameters Left, Top, Width and Height are directly updated in the Designer. You can also modify the Left, Top, Width and Height parameters directly in the Designer.Let us change the parameters of this first Label according to our requirements.By default, the name is Label with a number, here Label1, let us change its name to lblNumber1.The three letters lbl at the beginning for Label, and Number1 for the first number.It is recommended to use significant names for views so we know directly what kind of view it isand its purpose.
    • Basic4Android 17 Beginners guide Pressing Return or clicking elsewhere will also change the Event Name parameter. We have now:Main: main moduleName: name of the viewType: type of the view, Label, this parameter cant of course be changedEvent Name: name of the routine that handles the events of the LabelParent: parent view the Label belongs to.Let us check and change the other parameters: Left, Top, Width and Height are OK. Enabled, Visible are OK Tag we leave it empty. Text, we set a default number, say 5 Typeface, Style are OK Horizontal Alignment: we set it to CENTER_HORIZONTAL Vertical Alignment: we leave CENTER_VERTICAL. Size: we set it to 36 We leave all the other parameters as they are.
    • Beginners Guide 18 Basic4Android The new parameters.We need a second label similar to the first one. Instead of adding a new one, we copy the first onewith the same parameters. Only the Name, Left and Top parameters will change.
    • Basic4Android 19 Beginners guideLet us position the new Label and change its name to lblNumber2.Let us now add a 3rd Label for the math sign. We copy once again lblNumber1.Click on lblNumber1 in the Emulator, and in the Designer click in the Tools menu on DuplicateSelected View.Position it between the two first Labels and change its name to lblMathSign and its Text parameterto +.
    • Beginners Guide 20 Basic4AndroidNow let us add an EditText view. In the Designer click onPosition it below the three Labels and change its name to edtResult. edt for EditText and Resultfor its purpose. Let us change these parameters. Name to edtResult Horizontal Alignment to CENTER_HORIZONTAL Text Size to 30 Input Type to NUMBERS Hint Text to Enter result
    • Basic4Android 21 Beginners guideLet us add the Button to confirm the result or to generate a new calculation.Position it below the EditText view; resize it and change following parameters: Name: to btnAction Text: to O K and Text Size to 24.
    • Beginners Guide 22 Basic4AndroidLet us add the last Label for the comments, position it below the Button and resize it. Change the following parameters: Name to lblComments Horizontal Alignment: CENTER_HORIZONTAL Text Color to Black Color to White Alpha to 255 By default, the Label background color is black and transparent. We set it to white and opaque Alpha = 255. We set the Text color to black.
    • Basic4Android 23 Beginners guideLet us save the layout in a file.Click on and save it with the name Main. Click on .To write the routines for the project we need to reference the views in the code.This can be done with the Generate Members tool in the Designer.
    • Beginners Guide 24 Basic4AndroidThe Generate Members tool allows to automatically generate references and subroutine frames.Click on to open the generator.Here we find all the views added to the current layout.We check all views and check the Click event for the btnAction Button.Checking a view generates its reference in the Globals Sub in the code. This isneeded to make the view recognized and allow the autocomplete function.Clicking on en event of a view generates the Sub frame for this event.Click on to generate the references and sub frame and .
    • Basic4Android 25 Beginners guideNow we go back to the IDE to enter the code.First, we need to load our layout file to the Activity in the Activity_Create Sub.- Enter Activity- Enter a dot- The autocomplete function shows automatically all the possible parameters of the view.- Enter L , the autocomplete function shows the parameters beginning with L- Press the down arrow key, LoadLayout will appear with the online help for the given parameter ormethod.
    • Beginners Guide 26 Basic4Android- Press Return, LoadLayout is added.- Enter (, the online help is displayed showing the needed parameters for the method.- Enter "Main")We want to generate a new problem directly when the program starts. Therefore, we add a call tothe New subroutine.To generate a new problem, that means generate two random numbers Number1 and Number2between 1 and 9 and show them in the lblNumber1 and lblNumber2 Labels.To do this we enter following code:In Sub Globals we add two variables for the two numbers.And the New Subroutine:Rnd(1, 10) Random number generator, 1 min. number inclusive and 10 max. number exclusive.lblComments.Text = "Enter the result" & CRLF & "and click on OK"Displays the comment in lblComments. CRLF is the LineFeed character.
    • Basic4Android 27 Beginners guideNow we add the code for the Button click event.We have two cases:- When the Button text is equal to "O K" this means that a new problem is proposed and theprogram waits for the user entering a result and then pressing the Button.- When the Button text is equal to "NEW" this means that the user has entered a correct answer andwhen the user clicks on the Button a new problem will be generated.If btnAction.Text = "O K" Then checks if the Button text equals "O K"If yes then we check if the EditText is empty. If yes, we display a MessageBox telling the user that there is no result in the EditText view. If no, we check if the result is correct or if it is false.If no then we generate a new problem, set the Button text to "O K" and clear the EditText view.The last routine is the checking of the result.With If edtResult.Text = Number1 + Number2 Then we check if the result is OK.If yes, we display in the lblComments label the text below: G O O D result Click on NEW and we change the Button text to "N E W ".If no, we display in the lblComments label the text below: W R O N G result Enter a new result and click OK
    • Beginners Guide 28 Basic4AndroidLet us now compile the program and transfer it to the Emulator.We have not yet set the package name so the IDE asks for it. Enter B4A.MyFirstProgram. Click on .We need also to enter the Label name Click on .These two parameters can also be changed in the IDE in the Project menu.The program is going to be compiled.When you see Completed successfully. in above message box, the compiling and transfer isfinished.Look at the emulator, you should see something similar to the image below, with different numbers.
    • Basic4Android 29 Beginners guideOf course, we could make aesthetic improvements in the layout, but this was not the main issue forthe first program.
    • Beginners Guide 30 Basic4Android3 Second program (SecondProgram.b4a)Improvements of My first program.Create a new folder SecondProgram. Copy the all the files and folders from MyFirstProgram to thenew SecondProgram folder and rename the program file MyFirstProgram.b4a toSecondProgram.b4a . Load this new program in the IDE. Run the Designer and connect it to the Emulator. Let us add a numeric keyboard to the layout to avoid the use of the virtual keyboard. We need to change the Package Name. In the IDE Project menu. Click on Project Name Change the name to B4A.SecondProgram. Click on . And change the Application Label. Click on Application Label in the same menu. Change the name to SecondProgram. Click on .
    • Basic4Android 31 Beginners guideWe want to replace the edtResult EditText view by a new Label.In the Emulator and the Designer. Click on the edtResult view. Click on Click on lblNumber1 to select it. Duplicate it
    • Beginners Guide 32 Basic4Android Move it between the upper labels and the button and resize it. Modify following parameters: Name to lblResult Text to " " blanc character Text Color to Black Corner Radius to 5 Color to White Alpha to 255
    • Basic4Android 33 Beginners guide Let us add a Panel for the keyboard buttons. Position and resize it as in the image. Change its name to pnlKeyboard "pnl" for Panel, the view type. Change Corner Radius to 0
    • Beginners Guide 34 Basic4Android We will move the O K button from the Activity to the pnlKeyboard Panel. Click on The button belongs now to the Panel Move Label lblComments up near Label lblResult and increase the height of Panel pnlKeyboard like in the image.
    • Basic4Android 35 Beginners guide Click on the pnlKeyboard panel to select it. Click on to add a new button. The new button is added. Change following parameters. Name to btn0 Event name to btnEvent Left to 10 Top to 120 Width to 55 Height to 55 Tag to 0 Text to 0 Size to 24 Now we want to change the button colors. Click on StatelistDrawable. Click on GradientDrawable
    • Beginners Guide 36 Basic4Android Change the following parameters. Orientation to TOP_BOTTOM First Color Second Color Pressed Drawable to GradientDrawable Orientation to TOP_BOTTOM First Color Second Color The button looks now like this. Let us duplicate btn0 and position it besides button btn0. Change following parameters. Name to btn1 Tag to 1 Text to 1 Let us add 8 more Buttons and position them like in the image. Change following parameters: Name btn2, btn3, btn4 etc Tag 2 , 3 , 4 etc Text 2 , 3 , 4 etc
    • Basic4Android 37 Beginners guide Duplicate one of the number buttons, and position it like in the image. Resize and position btnOK. Change the pnlKeyboard Color to Black. Change their Name, Tag, Text and Color parameters as below. btnBS < btnOK OK
    • Beginners Guide 38 Basic4Android The finished new layout.Now we will update the code.First, we must replace the edtResult by lblResult because we replaced the EditText view by a Label. Click on edtResult to select it. Click on Find(F3)
    • Basic4Android 39 Beginners guide Click onClick on and .We need also to change its view type form EditText to Label.Now we write the routine, that handles the Click events of the Buttons.The Event Name for all buttons, excepted btnAction, is "btnEvent".The routine name will become btnEvent_Click, let us enter following code:We need to know what button raised the event. For this, we use the Sender object. To have access to the parameters of the view that raised the event we declare a local view variable Dim Send As Button. And set Send = Sender. Then to make the difference between the backspace button and the numeric buttons we use a Select / Case / End Select structure and use the Tag parameter of the buttons. Remember, when we added the different buttons we set their Tag parameter to BS, 0, 1, 2 etc.Select Send.Tag sets the variable to test.Case "BS" checks if it is the button with the "BS" tag value.Case Else handles all the other buttons.
    • Beginners Guide 40 Basic4AndroidNow we add the code for the numeric buttons.We want to add the value of the button to the text in the lblResult Label.This is done in line 75 withlblResult.Text = lblResult.Text & Send.TagThe "&" character means concatenation, so we just append to the already existing text the Tag valueof the button that raised the event.Now we add the code for the BackSpace button.When clicking on the BS button we must remove the last character from the existing text inlblResult.However, this is only valid if the length of the text is bigger than 0. This is checked with:If lblResult.Text.Length >0 ThenTo remove the last character we use the SubString2 function.lblResult.Text = lblResult.Text.SubString2(0,lblResult.Text.Length - 1)SubStrin2(BeginIndex, EndIndex) extracts a new string beginning at BeginIndex (inclusive) untilEndIndex (exclucive).Now the whole routine is finished.
    • Basic4Android 41 Beginners guideWe can try to improve the user interface of the program in adding some colors to the lblCommentsLabel.Let us set:- Yellow for a new problem- Light Green for a GOOD answer- Light Red for a WRONG answer.Let us first modify the New routine, where we add line 55.And in the CheckResult routine we add lines 62 and 66.
    • Beginners Guide 42 Basic4AndroidAnother improvement would be to hide the 0 button to avoid entering a leading 0.For this, we hide the button in the New subroutine in line 57.In addition, in the btnEvent_Click subroutine, we hide the button if the length of the text inlblResult is equal to zero and show it if the length is higher than zero, lines 85 to 89.
    • Basic4Android 43 Beginners guide4 The IDEThe Integrated Development Environment.When you run the IDE you will get a form like the image below:Example: SecondProgram.b4a.
    • Beginners Guide 44 Basic4Android4.1 Menu and Toolbar4.1.1 Toolbar Generates a new empty project. Loads a project. Saves the current project. Copies the selected text to the clipboard. Cuts the selected text and copies it to the clipboard. Pastes the text in the clipboard at the cursor position. Undoes the last operation. Redoes the previous operation. Activates the Find and Replace function. Sets the selected lines as comments. Uncomments the selected lines. Adds a bookmark. Removes a bookmark. Go back to the previous bookmark. Go forward to the next bookmark. Autocomplete function Ctrl + space. Decrease the indentation of the selected lines. Increase the indentation of the selected lines. Runs the compiler.
    • Basic4Android 45 Beginners guide4.1.2 File menu New Generates a new empty project. Open Source Loads a project. Save Saves the current project. Export As Zip Exports the whole project in a zip file. Page Setup Pages setup for printing Print Preview Shows a print preview. Print Prints the code. List of the last loaded programs.4.1.3 Edit menu Cut Cuts the selected text and copies it to the clipboard. Cut Line Cuts the line at the cursor position. Copy Copies the selected text to the clipboard. Paste Pastes the text in the clipboard at the cursor position. Undo Undoes the last operation. Redo Redoes the previous operation. Find Activates the Find and Replace function. Block Comment Sets the selected lines as comments. Block Uncomment Uncomments the selected lines. Remove All Bookmarks Bookmarks. Remove All Breakpoints Breakpoints. Outlining Collapse the whole code.
    • Beginners Guide 46 Basic4Android4.1.4 Project menu Adds a new module Add an existing module Changes the module name Removes the current module Hides the current module Activity properties, see below. Chooses an icon for the program. Changes the package name. Changes the Application name. Changes the Application version. Checked, the program is installed on an external storage. Orientations supported, see below. Different compiling modes. DebuggingActivity propertiesThe program can be full screen or notThe program can include the title bar or not.Orientations supported Both modes. Portrait only. Landscape only.
    • Basic4Android 47 Beginners guide4.1.5 Tools menu IDE Options see below Clean Files see below Clean Project see below Run AVD Manager Configure Paths Change Tab size. Change Font., not recommended. Word wrap, see below. Auto Save, see below.Show Tooltips, see below.Word wrapWithout word wrap. The end of the line is hidden.With word wrap. The end of the line is wrapped to the next line.Auto SaveSaves the program when you run it.Show Tooltips During Typing Show Tooltips checked. Show Tooltips unchecked.
    • Beginners Guide 48 Basic4Android4.2 Code areaThe code of the selected module is displayed in this area and can be edited.The examples below are based on the code of the SecondProgram.4.2.1 Undo – RedoIn the IDE it is possible to undo the previous operations and redo undone operations.Click on to undo and on to redo.4.2.2 Collapse a subroutineIn the IDE a subroutine can be collapsed to minimize the number of lines displayed.The btnAction_Click routine expanded. Click on the small square left to Sub to collapse the subroutine.The btnAction_Click routine collapsed.Hovering with the mouse over the collapsed routine name shows its content.
    • Basic4Android 49 Beginners guide4.2.3 Collapse the whole code In the Edit menu there are two functions allowing collapsing or expanding the whole code. The whole code collapsed. Hovering with the mouse over a subroutine still shows the beginning of its content.
    • Beginners Guide 50 Basic4Android4.2.4 Commenting and uncommenting codeA selected part of the code can be set to comment lines or set to normal. Original code Select the code. Click on . Lines set as comments. To set the lines to normal. Select the lines and click on .4.2.5 BookmarksYou can set bookmarks everywhere in the code and jump forward and backwards between thesebookmarks. To set a bookmark, position the cursor on the desired line, 12 in this example. Click on . The bookmark sign is displayed in the left margin. To remove a bookmark, position the cursor on the line and click on .Click on to jump forward to the next bookmark.Click on to jump backward to the previous bookmark.In the menu you can remove all bookmarks
    • Basic4Android 51 Beginners guide4.2.6 IndentationA good practice is to use the indentation of code parts.For example for subroutines, loops, structures etc. This code is difficult to read because the structure of the code is not obvious. This code is much easier to read, the structure of the code is in evidence. A tabulation value of 2 for the indentation is a good value. Example with an indentation of 4 Personally, I prefer a value of 2.
    • Beginners Guide 52 Basic4AndroidWhole blocks of code can be indented forth and back at once. Original code Select the code block. Click on . The whole block has moved one tabulation to the right. To move a block to the left. Select the code and click on .The indentation value can be changed in the Tools menu.Enter the value and click on .
    • Basic4Android 53 Beginners guide4.2.7 AutocompleteA very useful tool is the autocomplete function.Example: Let us write lblN Click on Ctrl + Space or . All variables, views and parameter names beginning with the letters already written are shown in a popup menu with the online help for the highlighted variable, view or parameter name. To choose lblNumber1 click on Return. To choose lblNumber2 click on the down arrow and click on Return. The selected name is completed. Now writing a dot All parameters and methods are displayed in a popup menu. When clicking on an item, the internal help is displayed Clicking on the up / down arrows selects the previous or next item with its help. Writing a character updates the list and shows the parameter beginning with that character.The best way to learn it is to play with it.
    • Beginners Guide 54 Basic4AndroidA second Autocomplete function allows you to create event subroutines.Enter the Sub word plus a blanc character.Press Tab.Select the type, Button in our example.Select the type, Click in our example.The subroutine frame is generated.Modify EventName to the EventName of the button, bntOK in our case.The routine is ready.
    • Basic4Android 55 Beginners guide4.2.8 DebuggingTo allow debugging you must activate the Debugger option. In the IDE in the Project menu Click on Attach Debugger.If this option is checked then the compiled code will contain debugging code.The debugging code allows the IDE to connect to the program and inspect it while it runs.When the program starts, it will wait for up to 10 seconds for the IDE to connect. Usually the IDEwill connect immediately. However if you run your program manually from the phone you will seeit waiting.The name of the compiled APK file will end with _DEBUG.apk. You should not distribute this apkfile as it contains the debugging code which adds a significant overhead.Another relevant option in this menu is Include Debug Information. This option doesnt have anyeffect when the Attach Debugger option is checked.When Attach Debugger is not checked (which means that debugging code will not be added) thisoption determines whether the original B4A code will be added to the compiled APK file. AddingB4A code is useful for one specific reason. During an exception the message will include theoriginal B4A line and not just the Java line.When we run the program with Attach Debugger checked the IDE will open the debugger moduleat the bottom of the screen:Notes about the debugger:- Breakpoints in the following subs will be ignored: Globals, Process_Globals and Activity_Pause.- Services - Breakpoints that appear after a call to StartService will be ignored. Breakpoints set inService_Create and Service_Start will pause the program for up to a specific time (about 12seconds). This is to avoid the OS from killing the Service.- Events that fire when the program is paused will be executed. Breakpoints in the event code willbe ignored (only when the program is already paused).- The data sent from the device to the IDE is limited in size. Long strings may be truncated.
    • Beginners Guide 56 Basic4AndroidThe two major utilities for debugging are:Breakpoints - You can mark lines of codes as breakpoints. This is done by pressing on the grey arealeft of the line.The program will pause when it reaches a breakpoint and will allow you to inspect the current state.Logging - The Logs tab at the right pane is very useful. It shows messages related to thecomponents life cycle and it can also show messages that are printed with the Log keyword. Youshould press on the Connect button to connect to the device logs. Note that there is a Filtercheckbox. When it is checked you will only see messages related to your program. When it isunchecked you will see all the messages running in the system. If you are encountering an error anddo not see any relevant message in the log, it is worth unchecking the filter option and looking foran error message.Note that the log is maintained by the device. When you connect to a device you will also seeprevious messages.
    • Basic4Android 57 Beginners guide4.2.9 BreakpointsClicking on a line in the left margin adds a breakpoint. When the program is running it stopsrunning at the first breakpoint.Run the program, the program stops at the breakpoint and the IDE looks like below. The breakpointline is highlighted in yellow..At the bottom of the IDE you find other information. Debugger is connected. Double click to detach the Debuger. Name of the routine where the program stopped. New routine at line 52. Calling routine of the New routine. Activity_Create routine in line 24. Clicking on these links jumps the cursor to the given line.
    • Beginners Guide 58 Basic4Android Continue code execution equivalent to F5. Continues the execution until the end or the next breakpoint. Step to the next line equivalent to F8. Continues the execution to the next line, very interesting during debugging to see the real program flow and the evolution of variable values. Pause the code as soon as possible. Stop the current program equivalent to F11. Stops also the program in the Emulator. Stopping the program in the Emulator doesnt stop it in the IDE ! Global variables. List of the global objects and variables used by the program with their values and parameters.Examples:btnAction: Type = Button Left = 190 Top = 0 Width = 115 Height = 55 Tag = empty Text = OKNumber1 = 6 Local variables. None in this example. Hovering with the mouse over a variable shows its value.Hovering with the mouse over a view shows its parameters like in the list.
    • Basic4Android 59 Beginners guideLet us run the program step by step: Set a breakpoint at line 50. Run the program click on or F5. The program will stop at line 50. Values of the two numbers in the Global variables window, it has been reduced to just show the two numbers. Click on F8. The program executes the next code line. The value of Number1 has changed ! Click on F8. The program executes the next code line. The value of Number2 has changed !
    • Beginners Guide 60 Basic4Android4.3 TabsOn the bottom right of the IDE there are 4 tabs,allowing showing either:4.3.1 Module and subroutine listsAll the modules of the project and all subroutines of the selected module are listed in two lists at theright of the IDE. Module list Clicking on a module shows its code in the code area. Subroutine list of the selected module Clicking on a subroutine shows its code in the middle of the code area.
    • Basic4Android 61 Beginners guide4.3.2 FilesThis window lists all the files that have been added to the project.These files are saved in the Files.DirAssets folder.These can be any kind of files: layouts, images, texts, etc. Clicking on allows to add files to the list. The files in that folder can be accessed with File.DirAssets. Checking one or more files enables the button. Clicking on this one removes the selected files from the list and from the Files folder of the project.
    • Beginners Guide 62 Basic4Android4.3.3 LogsDisplay of Log comments generated by the program when it is running.We add the two lines 51 and 53 in the program SecondProgram in the New routine.Run the program.Click on to connect the logger. In the window we see the flow of the program. Activity (main) Create, isFirst = true First log message Second log message Activity (main) Resume When it is checked you will only see messages related to your program. When it isunchecked you will see all the messages running in the system. If you are encountering an error anddo not see any relevant message in the log, it is worth unchecking the filter option and looking foran error messageClick to clear the Logs window.
    • Basic4Android 63 Beginners guide4.3.4 LibsList of the available libraries that can be used in the project.Check the libraries you need for your project.Make sure that you have the latest version of the libraries.The documentation for libraries can be found here:Basic4android - Android programming with Gui designer
    • Beginners Guide 64 Basic4Android5 Screen sizes and resolutionsThere exist many different screen sizes with different resolutions and pixel densities.We must make the difference between following parameters.- Physical screen size Ex: 3.6 diagonal- Resolution in pixels Ex: 320 / 480- Density pixels per inch Ex: 160The standard screen is 320 / 480 pixels, density 160 pixels/inch.There exist other screens with almost the same physical size but with a higher resolution forexample 480 / 640 pixels with a density of 240 pixels/inch.Tablets have bigger physical sizes but can have a density similar to the standard screen.Example: 7.2 screen diagonal, 640 / 960 pixels and a density of 160 pixels/inch.A non-exhaustive list of screens: Diagonal Resolution Density Scale W / H Ratio 3.6 320 / 480 160 1 3/2 3.6 480 / 720 240 1.5 3/2 3.9 480 / 800 240 1.5 5/3 3.6 240 / 320 120 0.75 4/3 7.2 640 / 960 160 1 3/2 10 720 / 1280 160 1 16 / 9Let us compare the following resolutions:1) 320 / 480 / 160 screen ~3.5 standard density 1602) 640 / 960 / 320 screen ~3.5 density 3203) 640 / 960 / 160 ~7 screen standard density 160In cases 1) and 2) the physical sizes of the screens are the same but the density of the pixels isdifferent.In cases 1) and 3) the densities are the same but the physical dimensions of the screen in case 3)are the double of those of the screen in case 1) giving a surface 4 times bigger.Let us look at the size of a button with 80 / 80 dip, its physical size. dips pixels inch1) 80 80 0.52) 80 120 0.52) -- 80 0.375 dimension given in pixels not in dips3) 80 80 0.5It is possible to generate special Emulators with special sizes, resolutions and densities.
    • Basic4Android 65 Beginners guideA same layout file can fit into different screen resolutions, but with some restrictions.We will use the TestLayouts program to test the same layout with different screen resolutions.The different resolutions are: Screen Density H / W ratio Height pixels Pixel diff. resolution 240 / 320 120 3/2 360 - 40 320 / 480 160 4/3 480 0 480 / 800 240 5/3 720 + 80The reference resolution is 320 / 480 with a density of 160.If we calculate, for the two other resolutions, the equivalent height using the same H/W ration weget the equivalent height in pixels and the difference in pixels.This means that with the same layout file for all three resolutions there will be 40 pixels missingwith the 240/320 resolution and 80 extra pixels with the 480/800 resolution. The original layout in the standard 320/480 pixels density 160 Emulator is the following. To make the tests we need three emulators: - 320 / 480 density 160 - 240 / 320 density 120 - 480 / 800 density 240 If you do not have these emulators, you must create them in the AVD Manager. Look here to generate an Emulator.And the code is:Note that lines 23 and 24 are commented out !
    • Beginners Guide 66 Basic4AndroidTests with the three Emulators with different resolutions and different densities. 480 / 800 240 320 / 480 160 240 / 320 120The image sizes are reduced by a factor of 0.5 for easier comparison.What we see: - with the standard resolution, the image in the emulator is equal to the original layout. - with the 240/320 resolution we see that there are the expected 40 pixels missing. - with the 480/800 resolution, we see that there are the expected 80 extra pixel.The numbers of items in the ListView are the same for all three resolutions.
    • Basic4Android 67 Beginners guideSecond test with lines 23 and 24 activated.In line 23 we calculate the top of the pnlToolBox panel according to the screen height.In line 24 we calculate the ListView height according to the top of the pnlToolBox.What we see: - with the standard resolution, the image in the emulator is still equal to the original layout. - with the 240/320 resolution we see that the buttons are at the bottom of the screen but the ListView height is shortened. - with the 480/800 resolution we see that the buttons are at the bottom and the ListView is higher.The numbers of items in the ListView are different in the three layouts because the ListView heighthas been adapted to the different relative screen heights.In the first test, the number of items in the ListView were the same !These examples show that it is not easy to have one layout for different screen resolutions.In the example above it was relatively easy because the view in the middle is easily adjustable.
    • Beginners Guide 68 Basic4AndroidEven when we load the layout file in the three emulators with resolutions 480 / 800, 320 / 480 and240 / 320 pixels the layout is stretched or shrinked according to the screen size, but we see of coursealso the extra and missing pixels depending on the different relative screen heights.The Android OS autoscale system adjusts the Left, Top, Width, Height, FontSize and otherparameters with the scale factor but does NOT resize the vertical positions nor the heights of theviews proportional to the screen height. The same is valid for the width in landscape mode.
    • Basic4Android 69 Beginners guide6 The EmulatorThe Emulator or Virtual Device is a program that simulates devices on the PC.6.1 Launch an EmulatorTo launch an Emulator click in the IDE in the Tools menu on Run AVD Manager..Select the desired emulator.The portrait Emulator in this case. Click on Click on
    • Beginners Guide 70 Basic4AndroidWait until the Emulator is ready, this will take quite some time.
    • Basic4Android 71 Beginners guide6.2 Generate a new EmulatorLet us add a new Emulator with a resolution of 480 / 800 pixels, density 240.In the AVD ManagerClick on Enter the name Emulator 480_800 Select Android 2.2 – API Level 8 Enter 16. Enter 480 and 800 Click on Click on .
    • Beginners Guide 72 Basic4Android Change 160 to 240. Click on . Click on .The new Emulator is added.
    • Basic4Android 73 Beginners guide6.3 Emulator problemsUnfortunately, the Emulator is quite slow and sometimes a pain.When you either run the program or connect the Emulator from the Designer, sometimes you willsee the message below. You have two options: - Yes (Oui) to cancel the process. - No (Non) Continue the process.Press , most times continuing the process will succeed.But, even after having clicked on continue, sometimes you will see this message.Run the program once more, in most cases the Emulator will be connected and work well.This often happens when the Emulator is still running a program or if the Emulator is stillconnected to another project. In this case press the back button until you reach the Emulators homescreen, and try again.If this happens, a second time, close the current Emulator and run it again from the AVD Manager.If the first message above appears too often you can increase the timeout value in the b4aV0.1.inifile.The file is located in:XP: C:Documents and Settings<user>Application DataAnywhere SoftwareBasic4androidVista / 7: C:Users<user>AppDataRoamingAnywhere SoftwareBasic4androidand set the ProcessesTimeoutSeconds parameter to a higher value.I set it to 45 seconds : ProcessesTimeoutSeconds=45.
    • Beginners Guide 74 Basic4Android7 B4A BridgeUp until now there were two methods for testing your application during development.You can either work with the Android emulator or if your device supports ADB debugging, youwere able to connect to your real device.The Android emulator is very slow compared to a real device (especially with applicationsinstallation).Therefore in most cases it is more convenient to work with a real device.Personally, Im only using the emulator when working with the visual designer.However not all devices support ADB debugging. This is exactly the reason for the new B4A-Bridge tool.B4A-Bridge is made of two components. One component runs on the device and allows the secondcomponent which is part of the IDE to connect and communicate with the device.The connection is done over a network (B4A-Bridge cannot work if there is no network available).Once connected, B4A-Bridge supports all of the IDE features which include: installing applications,viewing LogCat and the visual designer.Android doesnt allow applications to quietly install other applications, therefore when you run yourapplication using B4A-Bridge you will see a dialog asking for your approval.Getting started with B4A-Bridge1. First you need to install B4A-Bridge on your device.B4A-Bridge can be downloaded here: http://www.basic4ppc.com/android/files/b4a_bridge.apk.B4A-Bridge is also available in Android market. Search for: B4A Bridge.Note that you need to allow install of applications from "Unknown sources". This is done bychoosing Settings from the Home screen - Manage Applications.2. Run B4A-Bridge on your device. It will display a screen similar to:Status will be: Waiting for connections.
    • Basic4Android 75 Beginners guide3. In the IDE choose Tools - B4A Bridge - Connect.You will need to enter the IP address that appears on the device screen.The status bar at the bottom of the screen shows the current status:Thats it.When B4A-Bridge gets connected it first checks if the designer application needs to be updated. Inthat case it will first install the designer application.B4A-Bridge keeps running as a service until you press on the Stop button.You can always reach it by opening the notifications screen:Pressing on the notification will open the main screen.As mentioned above, when you run an application you are required to approve the installation. Youwill usually see the following screens:
    • Beginners Guide 76 Basic4AndroidIn the above dialog you should choose Open to start the application.If you try to install an existing application signed with a different key, the install will fail (withoutany meaningful message). You should first uninstall the existing application. Go to the home screen- Settings - Applications - Manage applications - choose the application - Uninstall.Once you finished developing you should press on the Stop button in order to save battery.Note that B4A-Bridge was written with Basic4android.The source code is available here: http://www.basic4ppc.com/forum/basic...html#post45854
    • Basic4Android 77 Beginners guide8 The DesignerThe Designer allows generating layouts with either the Emulator or a real device.
    • Beginners Guide 78 Basic4Android8.1 The menu8.1.1 File menu New Opens a new empty layout. Open Opens an existing layout. Save Saves the current layout. Save As… Saves the current layout with a new name. Main Layout file list, in this case only one file, Main.8.1.2 AddView menu This menu allows you to select the view you want to add on the current layout on the device or the Emulator. Button adds a Button CheckBox adds a CheckBox EditText adds an EditText ImageView adds an ImageView Label adds a Label ListView adds a ListView Panel adds a Panel ProgressBar adds a ProgressBar RadioButton adds a RadioButton ScrollView adds a Scrollview SeekBar adds a SeekBar Spinner adds a Spinner TabHost adds a TabHost ToggleButton adds a ToggleButton WebView adds a WebView
    • Basic4Android 79 Beginners guide8.1.3 The Tools menu Generate Members Members generator Bring to Front Brings the selected View to front Duplicate Selected View Duplicates the selected View Remove Selected View Removes the selected View Change Grid Allows to change the grid size Connect Connects the Emulator or the device Disconnect Disconnects the Emulator or the device
    • Beginners Guide 80 Basic4Android8.2 Tools8.2.1 Generate MembersAllows generating Dim statements and frames for subroutines.The Generate Members tool allows to automatically generate references and subroutine frames. Click on to open the generator.Here we find all the views added to the current layout.We check all views and check the Click event for the btnAction Button.Checking a view generates its reference in the Globals Sub in the code. This isneeded to make the view recognized and allow the autocomplete function.Clicking on en event of a view generates the Sub frame for this event.Click on to generate the references and sub frame and .
    • Basic4Android 81 Beginners guide8.2.2 BringTo Front When views are overlapping, the hidden or partial hidden view can be brought to front. Click on the view to bring to front to select it. Click on to bring the selected view to front. This is especially interesting with big Panels.8.2.3 Duplicate Selected View Click on the view you want to duplicate to select it. Click on to duplicate the view. The view is duplicated.
    • Beginners Guide 82 Basic4Android8.2.4 Remove Selected View Click on the view to remove to select it. Click on to remove it. The view has been removed. Note: Be careful, you will not be asked if you really want to remove the view.8.2.5 Change gridThe grid is an invisible grid with a given size. The default grid size is 10 pixels. That means that allpositions and dimensions of a view will be set to values in steps corresponding to the grid size.Moving a view will be done in steps equal to the grid size.Click on You can change the grid size to the value you want.
    • Basic4Android 83 Beginners guide8.2.6 Connect device or emulatorClick on to connect a device or an Emulator.If different devices or Emulators are connected, you will be asked what device or Emulator youwant to connect. Select the device in the list. Click on to confirm.8.3 General settings Shows the Designer state, in this case the Designer is connected. Selects the current view to edit. The window can be set to stay always on TOP.
    • Beginners Guide 84 Basic4Android8.4 Image files You can add image files to the layout. Click on to select the files(s) to add. These files will be listed in the Image Files list. These files are saved to the Files folder of the project. To remove files, check the files to remove and click on .
    • Basic4Android 85 Beginners guide8.5 Parameter list List of the parameters for the selected view organized in groups. All parameters can be modified directly in the list. All parameters in the Main group and some of the parameters in the other groups are common to all view types.Explanation of some general parameters for all types of Views:Name Name of the view. It is good practice to give meaningful names. Commonusage is to give a 3 character prefix and add the purpose of the view. In the example, the view is oftype Label and its purpose is to enter a result. So we give it the name "lblResult", "lbl" forEditText and "Result" for the purpose. This does not take much time during the design of the layoutbut saves a lot time during coding and maintenance of the program.Type Type of the view, not editable. It is not possible to change the type of a view.If you need to, you must remove the view and add a new one.Event Name Generic name for the subroutines that manages the views events. By default,the Event Name is the same as the views name like in the example. The Events of several Viewscan be redirected to a same subroutine. In that case you must enter the name of that routine.Look at the SecondProgram example for the Click event management for the buttons of thekeyboard, the btnEvent_Click routine.
    • Beginners Guide 86 Basic4AndroidParent Name of the parent view. Activity, in the example. The parent view can bechanged in selecting the new one in the list.Left X coordinate of the left edge of the View from the left edge of its parentView, in pixels.Top Y coordinate of the upper edge of the View from the upper edge of its parentView, in pixels.Width Width of the View in pixels.Height Height of the View in pixels.Enabled Enables or disables the use of the View Ex: Enabled = TrueVisible Determines if the View is visible to the user or not.Tag This is a place holder which can used to store additional data. Tag can simplybe text but can also be any other kind of object. Tag is used in the SecondProgram example for thenumeric buttons click events management in the btnEvent_Click routine.
    • Basic4Android 87 Beginners guide8.6 Layout variants Different layout variants can be managed in a same layout file.Let us make an example based on the TestLayouts project:- Copy the whole TestLayouts folder.- Rename it to TestLayoutVariants.- Rename the TestLayout.b4a file to TestLayoutVariants.b4a.- Run the IDE.- Run the Emulator (320 * 480 - 160)- Run the Designer.- Connect the Designer to the Emulator or the device.The emulator should look like this.
    • Beginners Guide 88 Basic4Android In the Designer, click on . Select: 480 x 320 scale = 1 Click on . The new variant is added.Go to the Emulator, press Ctrl + F11, to change it to landscape mode. It should look like this.
    • Basic4Android 89 Beginners guide The toolbox is not visible, to get it we select it in the Designer. And set its Top value to 10. The Toolbox is now visible. Let us rearrange the different views to adapt them to the landscape mode. Button height 65 ListBox1: Width = 380 Height = 220
    • Beginners Guide 90 Basic4AndroidIn the code we change the Activity_Create routine fromtoRun the program.The Emulator should look like this: Click on Ctrl + F11 to change to portrait >>>We have now two layout variants in the same layout file.
    • Basic4Android 91 Beginners guideWith the 320*240_120 emulator.
    • Beginners Guide 92 Basic4Android9 Process and Activity life cycleLets start simple:Each Basic4android program runs in its own process.A process has one main thread which is also named the UI thread which lives as long as the processlives. A process can also have more threads which are useful for background tasks.A process starts when the user launches your application, assuming that it is not running already inthe background.The process end is less determinant. It will happen sometime after the user or system has closed allthe activities.If for example you have one activity and the user pressed on the back key, the activity gets closed.Later when the phone gets low on memory (and eventually it will happen) the process will quit.If the user launches your program again and the process was not killed yet the same process will bereused.A Basic4android application is made of one or more activities. Android support several other"main" components. These will be added to Basic4android in the future.Activities are somewhat similar to Windows Forms.One major difference is that, while an activity is not in the foreground it can be killed in order topreserve memory. Usually you will want to save the state of the activity before it gets lost. Either ina persistent storage or in memory that is associated with the process.Later this activity will be recreated when needed.Another delicate point happens when there is a major configuration change in the device. The mostcommon is an orientation change (user rotates the device). When such a change occurs the currentactivities are destroyed and then recreated. Now when we create the activity we can create itaccording to the new configuration (for example, we now know the new screen dimensions).
    • Basic4Android 93 Beginners guideHow do we handle it?When you create a new activity you will start with the following code template:Variables can be either global or local. Local variables are variables that are declared inside a subother than Process_Globals or Globals.Local variables are local to the containing sub. Once the sub ends, these variables no longer exist.Global variables can be accessed from all subs.There are two types of global variables.Process variables and activity variables.Process variablesThese variables live as long as the process lives.You should declare these variables inside sub Process_Globals.This sub is called once when the process starts (this is true for all activities, not just the firstactivity).These variables are the only "public" variables. Which means that they can be accessed from othermodules as well.However, not all types of objects can be declared as process variables.All of the views for example cannot be declared as process variables.The reason is that we do not want to hold a reference to objects that should be destroyed togetherwith the activity.In other words, once the activity is being destroyed, all of the views which are contained in theactivity are being destroyed as well.If we hold a reference to a view, the garbage collector would not be able to free the resource and wewill have a memory leak.The compiler enforces this requirement.
    • Beginners Guide 94 Basic4AndroidActivity variablesThese variables are contained by the activity.You should declare these variables inside Sub Globals.These variables are "private" and can only be accessed from the current activity module.All objects types can be declared as activity variables.Every time the activity is created, Sub Globals is called (before Activity_Create).These variables exist as long as the activity exists.Sub Activity_Create (FirstTime As Boolean)This sub is called when the activity is created.The activity is created when the user first launches the application, the device configuration haschanged (user rotated the device) and the activity was destroyed, or when the activity was in thebackground and the OS decided to destroy it in order to free memory.This sub should be used to load or create the layout (among other uses).The FirstTime parameter tells us if this is the first time that this activity is created. First time relatesto the current process.You can use FirstTime to run all kinds of initializations related to the process variables.For example if you have a file with a list of values that you need to read, you can read it ifFirstTime is True and store the list as a process variable.Now we know that this list will be available as long as the process lives and there is no need toreload it even when the activity is recreated.To summarize, you can test whether FirstTime is True and then initialize process variables.
    • Basic4Android 95 Beginners guideSub Activity_Resume and Sub Activity_Pause (UserClosed As Boolean)Each time the activity moves from the foreground to the background Activity_Pause is called.Activity_Pause is also called when the activity is in the foreground and a configuration changeoccurs (which leads to the activity getting paused and then destroyed).Activity_Pause is the last place to save important information.Generally there are two types of mechanisms that allow you to save the activity state.Information that is only relevant to the current application instance can be stored in one or moreprocess variables.Other information should be stored in a persistent storage (file or database).For example, if the user changed some settings you should save the changes to a persistent storageat this point. Otherwise the changes may be lost.Activity_Resume is called right after Activity_Create finishes or after resuming a paused activity(activity moved to the background and now it returns to the foreground).Note that when you open a different activity (by calling StartActivity), the current activity is firstpaused and then the other activity will be created if needed and (always) resumed.As discussed above Activity_Pause is called every time that the activity moves from the foregroundto the background. This can happen because:1. A different activity was started.2. The Home button was pressed3. A configuration changed event was raised (orientation changed for example).4. The Back button was pressed.In scenarios 1 and 2, the activity will be paused and for now kept in memory as it is expected to bereused later.In scenario 3 the activity will be paused, destroyed and then created (and resumed) again.In scenario 4 the activity will be paused and destroyed. Pressing on the Back button is similar toclosing the activity. In this case you do not need to save any instance specific information (theposition of pacman in a PacMan game for example).The UserClosed parameter will be true in this scenario and false in all other. Note that it will also betrue when you call Activity.Finish. This method pauses and destroys the current activity, similar tothe Back button.You can use UserClosed parameter to decide which data to save and also whether to reset anyrelated process variables to their initial state (move pacman position to the center if the position is aprocess variable).
    • Beginners Guide 96 Basic4Android10 Variables and objectsA variable is a symbolic name given to some known or unknown quantity or information, for thepurpose of allowing the name to be used independently of the information it represents. A variablename in computer source code usually associated with a data storage location and thus also itscontents, and these may change during the course of program execution. (source Wikipedia)Basic4android type system is derived directly from Java type system.There are two types of variables: primitives and non-primitives types.Primitives include the numeric types: Byte, Short, Int, Long, Float and Double.Primitives also include: Boolean and Char.10.1 Variable TypesList of types with their ranges: B4A Type min value max value Boolean boolean False True - 27 27 - 1 Byte integer 8 bits -128 127 - 2 15 2 15 -1 Short integer 16 bits - 32768 32767 - 2 31 2 31 -1 Int integer 32 bits -2147483648 2147483647 - 2 63 2 63 -1 Long long integer 64 bits -9223372036854775808 9223372036854775807 -149 floating point number -2 (2 -2 -23) * 2 127 Float 32 bits 1.4E-45 3.4028235 E 38 double precision - 2 -1074 (2 -2 -52) * 2 1023 Double number 2.2250738585072014 E - 1.7976931348623157 E 64 bits 308 308 Char character String array of charactersPrimitive types are always passed by value to other subs or when assigned to other variables.For example: The variable A = 12 Its passed by value to routine S2 Variable A still equals 12, even though B was changed in routine S2. Variable B = 12 Its value is changed to B = 45
    • Basic4Android 97 Beginners guideAll other types, including arrays of primitives types and strings are categorized as non-primitivetypes.When you pass a non-primitive to a sub or when you assign it to a different variable, a copy of thereference is passed.This means that the data itself isnt duplicated.It is slightly different than passing by reference as you cannot change the reference of the originalvariable.All types can be treated as Objects.Collections like lists and maps work with Objects and therefore can store any value.Here is an example of a common mistake, where the developer tries to add several arrays to a list:10.2 Names of variablesIt is up to you give any name to a variable, except reserved words.A variable name must begin with a letter and must be composed by following characters A-Z, a-z,0-9, and underscore "_", no spaces, no brackets etc.Variable names are case insensitive, that means that Index and index refer to the same variable.But it is good practice to give them meaningful names.Example:Interest = Capital * Rate / 100 is meaningfuln1 = n2 * n3 / 100 not meaningfulFor Views it is useful to add to the name a three character prefix that defines its type.Examples:lblCapital lbl > Label Capital > purposeedtInterest edt > EditText Interest > purposebtnNext btn > Button Next > purpose10.3 Declaring variables10.3.1 Simple variablesVariables are declared with the Dim keyword followed by the variable name the As keyword andfollowed by the variable type. Examples: Declares three variables as Double, double precision numbers. Declares three variables as Int, integer numbers. Declares three variables as EditText views. Declares two variables as Button views.
    • Beginners Guide 98 Basic4AndroidThe same variables can also be declared in a short way.The names of the variables separated by commas and followed by the type declaration.View names must be declared when we want to use them in the code.If we want, for example, change the text in an EditText view in the code, likeedtCapital.Text = "1200",we need to reference this EditText view by its name edtCapital, this is done with the Dimdeclaration.If we never make any reference to this EditText view anywhere in the code no declaration isneeded.Using an event routine for that view doesnt need a declaration either.To allocate a value to a variable write its name followed by the equal sign and followed by thevalue, like:Capital = 1200LastName(0) = "SMITH"Note that for Capital we wrote just 1200 because Capital is a number.But for LastName(0) we wrote "SMITH" because LastName(0) is a string.Strings must always be written between double quotes.10.3.2 Array variablesArrays are collections of data or objects that can be selected by indices. Arrays can have multipledimensions.The declaration contains the Dim keyword followed by the variable name LastName, the number ofitems between brackets (50), the keyword As and the variable type String.Examples: One dimension array of strings, total number of items 50. Two dimensions array of Doubles, total number of items 9. Three dimensions array of integers, total number of items 150.The first index of each dimension in an array is 0.LastName(0), Matrix(0,0), Data(0,0,0)The last index is equal to the number of items in each dimension minus 1.LastName(4,9), Matrix(2,2), Data(2,4,9)
    • Basic4Android 99 Beginners guideorExample to access all items in the three dimensions array Data:A more versatile way to declare arrays is to use variables.We declare the variable Dim NbPers As Int and set its value to 10, NbPers = 10 .The colon ":" is a separator for two statement on the same line.Then we declare the arrays with this variable instead of the number 10 as before.The big advantage is that, if we need one time to change the number of items, we change only ONEvalue.For the Data array we could use the following code.And the access routine.
    • Beginners Guide 100 Basic4Android10.3.3 Type variablesLet us reuse the example with the data of a person.Instead of declaring each parameter separately, we can define a personal type variable with theType keyword:The new personal type is Person , then we declare either single variables or arrays of this personaltype.To access a particular item use following code.CurrentUser.FirstNameCurrentUser.LastNameUser(1).LastNameUser(1).FirstNameThe variable name, followed by a dot and the desired parameter.If the variable is an array then the name is followed by the desired index between brackets.It is possible to attribute a type variables to another one, of the same type, like below.
    • Basic4Android 101 Beginners guide10.4 CastingBasic4android casts types automatically as needed. It also converts numbers to strings and viceversa automatically.In many cases you need to explicitly cast an Object to a specific type.This can be done by assigning the Object to a variable of the required type.For example, Sender keyword returns an Object which is the object that raised the event.The following code changes the color of the pressed button.Note that there are multiple buttons that share the same event sub.The above code could also be written more elegantly:
    • Beginners Guide 102 Basic4Android10.5 Scope10.5.1 Process variablesThese variables live as long as the process lives.You should declare these variables inside sub Process_Globals.This sub is called once when the process starts (this is true for all activities, not just the firstactivity).These variables are the only "public" variables. Which means that they can be accessed from othermodules as well.However, not all types of objects can be declared as process variables.All of the views for example cannot be declared as process variables.The reason is that we do not want to hold a reference to objects that should be destroyed togetherwith the activity.In other words, once the activity is being destroyed, all of the views which are contained in theactivity are being destroyed as well.If we hold a reference to a view, the garbage collector would not be able to free the resource and wewill have a memory leak.The compiler enforces this requirement.10.5.2 Activity variablesThese variables are contained by the activity.You should declare these variables inside Sub Globals.These variables are "private" and can only be accessed from the current activity module.All objects types can be declared as activity variables.Every time the activity is created, Sub Globals is called (before Activity_Create).These variables exist as long as the activity exists.10.5.3 Local variablesVariables declared in a subroutine are local to this subroutine.They are "private" and can only be accessed from within the subroutine where they were declared.All objects types can be declared as local variables.At each call of the subroutine the local variables are initialized to their default value or to any othervalue you have defined in the code and are destroyed when the subroutine is left.
    • Basic4Android 103 Beginners guide10.6 TipsAll views types can be treated as Views. This allows you to change the common properties of viewseasily.For example, the following code disables all views that are direct children of the activity:If we only want to disable buttons:
    • Beginners Guide 104 Basic4Android11 Modules
    • Basic4Android 105 Beginners guide12 Example programs12.1 User interfacesLet us make three different user interfaces to select three different screens.The three user interfaces are: Menu TabHost view Button toolboxFor each test program there is a Main layout.For each of the three pages there is a layout file Page1, Page2 and Page3.Each layout file is loaded to a Panel or a TabHost panel.These layouts can contain whatever views you need.
    • Beginners Guide 106 Basic4Android12.1.1 Menu example (UserInterfaceMenu.b4a)The test program is: UserInterfaceMenu.b4a. The code is self explanatory. 1. Each page is on a Panel, pnlPage1, pnlPage2 and pnlPage3. 2. The Panels are added by code. 3. The page layout files are loaded to the Panels. 4. The Menu items are added to the Activity. 5. One Click event routine for each Menu item. It could also be done in one routine (like in UserInterfaceButtonToolbox.b4a).
    • Basic4Android 107 Beginners guide12.1.2 TabHost example (UserInterfaceTabHost.b4a)The test program is: UserInterfaceTabHost.b4a The code is self explanatory. 1. Each page is on a TabHost panel. 2. The TabHost view is in the Main layout. 3. The TabHost panels are added with the Page layout files.
    • Beginners Guide 108 Basic4Android12.1.3 Button toolbox example (UserInterfaceButtonToolbox.b4a)The test program is: UserInterfaceButtonToolbox.b4a The code is self explanatory. 1. Each page is on a Panel, pnlPage1, pnlPage2 and pnlPage3. 2. The Panels are added by code. 3. The page layout files are loaded to the Panels. 4. The Buttons are in the Main layout on the pnlToolBox panel. 5. One Click event routine for all Buttons.
    • Basic4Android 109 Beginners guide12.2 Program with 3 Activities (ThreeActivityExample.b4a)The test program is: ThreeActivityExample.b4aThe goal of the program is: - to show how to manage several Activities. - working with Process Global variables across different Activities. The variables can be changed in different activities, but are available over the whole project. - change layout parameters, in moving a small red panel over the screen. - save and load the layout parameters of the small red panel with a Map object so the square will keep the same position after changing a page or restarting the program.The program looks like below:We have: - 3 pages, each one in its own Activity. - 3 process global variables, Value1, Value2 and Value3 - on each page 1 EditText view to modify the Value variable with page index. - 2 Labels to display the two other variables. - on Page1 a small red square Panel to move around.We can: - Change Value1 in Page1. - Change Value2 in Page2. - Change Value3 in Page3. - Move the small red square over the screen. - Select either Page2 or Page3 on Page1.
    • Beginners Guide 110 Basic4AndroidLet us take the example with the Button toolbox (UserInterfaceButtonToolbox.b4a).Instead of having our three pages on three panels we will use 3 activities.Main, Page2 and Page 3.For this we must create two new Modules: Page2 and Page3. In the IDE click on. Enter the name Page2 and click on .A new module is added to the project.
    • Basic4Android 111 Beginners guideModify the code of Page2 module as below:Add now a new module "Page3" the same way as Page2 and modify the code like below:These codes are self explanatory.
    • Beginners Guide 112 Basic4AndroidLet us modify the code of the Main module:In Sub Process-Globals we add following variables.Value1, Value2 and Value3 to save some values.mapMoveTopLeft as a Map object to save the Left and Top parameter of the small red square.In Globals we have the variables below:lblValue2_P1 is the Label to display Value2 on page1.lblValue3_P1 is the Label to display Value3 on page1.edtValue1_P1 is the EditText to enter Value1 on page1.pnlPage1 is the container for the Page1 layout.pnlMove is the small red square.X0, Y0, X1 and Y1 are used to memorize initial coordinates when moving the red square.Sub Activity_Create is modified like below:When the routine is called the first time, we initialize the three Value variables.
    • Basic4Android 113 Beginners guideIn Sub Activity_Resume we initialize the parameters of the views of Activity Main.Init.txt is the file with the Left and Top parameters of the small red square pnlMove.If the file does exist we read it and set the Left and Top parameters of pnlMove.If the file doesnt exist we initialize the Map object and set the two first parameters to the Left andTop parameters of pnlMove..When the "Main" Activity is paused, due to either a page change or the program closing, we: - set variable Value1 to the edtValue1.Text contend. - save the Map to file Init.txt.To go back to Page1 from either Page2 or Page3, the user must press the Back key. To avoid thatthe program stops when the user clicks, by inadvertence, one time too much, we check in SubActivity_KeyPress what key was pressed. And if its the Back key we display a message in aMessageBox asking the user if he really wants to quit the program. If Yes, then we set the Returnvalue to False that means that the event is sent back to the OS to close the program. If the answer isNo, we set the Return value to True, that means that we consume the event and the OS will notstop the program.
    • Beginners Guide 114 Basic4AndroidTo show how to manage layout parameters we have the small red square, pnlMove, that can bemoved on the screen. The position of pnlMove is handled in Sub Activity_Touch where we getthree parameters: - Action holding the value of the action the user made. ACTION_DOWN the user touches the screen. ACTION_MOVE the user moves on the screen ACTION_UP the user leaves the screen - X the X coordinate of the finger on the screen. - Y the Y coordinate of the finger on the screen.To be able to move pnlMove we do the following: - when Action is equal to ACTION_DOWN, the user touches the screen we memorize the coordinates of the finger and the coordinates of the upper left corner of pnlMove (lines 76 to 79). - when Action is equal to ACTION_MOVE the user moves his finger on the screen. we calculate the relative displacement, dX and dY, in both directions and set the new Left and Top parameters of pnlMove (lines 82 to 85). - when Action is equal to ACTION_UP, the user leaves the screen we update the two parameters in the Map object (lines 88 and 89=.
    • Basic4Android 115 Beginners guideIn Sub btnPage_Click we start the Page Activity according to what button was pressed. - We declare a new Button object, Send. - We attribute Sender to Send . Sender is the buttom view that raised the event. - Depending on the Tag value of the sender object we start the correct Activity.We still need to modify the four layout files: Main: We remove btnPage1, no more needed. Enlarge the two remaining buttons and reposition them Page 1: We add the views like in the image at the left. Similar for Page 2 and Page 3. The layout files are in the project.
    • Beginners Guide 116 Basic4Android12.3 ScrollView example
    • Basic4Android 117 Beginners guide12.4 Data base example
    • Beginners Guide 118 Basic4Android13 Basic languageIn computer programming, BASIC (an acronym which stands for Beginners All-purpose SymbolicInstruction Code) is a family of high-level programming languages designed to be easy to use.The original Dartmouth BASIC was designed in 1964 by John George Kemeny and ThomasEugene Kurtz at Dartmouth College in New Hampshire, USA to provide computer access to non-science students. At the time, nearly all use of computers required writing custom software, whichwas something only scientists and mathematicians tended to do. The language and its variantsbecame widespread on microcomputers in the late 1970s and 1980s.BASIC remains popular to this day in a handful of highly modified dialects and new languagesinfluenced by BASIC such as Microsoft Visual Basic. (source Wikipedia).13.1 Program flowThis is a summary of the more detailed explanations in Process and Activity life cycle.The program goes through following routines when starting from top to down:13.1.1 Prorogress_Globals routineDedicated to the declaration of process global variables. Variables that are valid during the wholelife time of the process and accessible from everywhere in the program.
    • Basic4Android 119 Beginners guide13.1.2 Globals routineDedicated to the declaration of activity global variables. Variables that are valid only during the lifetime of the activity and accessible only insides the activity. As soon as the activity is paused, thesevariables are no more available.13.1.3 Activity_Create (FirstTime As Boolean) routineArea to initialize activity variables.If variables or objects must be initialized only once, the first time at the launch of the application,you can use the FirstTime parameter to check it.13.1.4 Activity_Resume routineThis routine is called every time an activity is launched or resumed, re-activated, Here you can setany setup parameters for the new current activity.13.1.5 Activity_Pause (UserClosed As Boolean) routineWhen the activity is going to be paused, this routine Activity_Pause is called.Here you need to save activity parameters you want to get back when the activity is resumed (re-activated)One of the most current reason why an activity is paused, is an orientation change.In that case the current activity is paused, and re-activated with the new orientation and goes atleast through the Activity_Resume routine, but normally through Globals, Activity_Create andActivity_Resume.The variable UserClosed can be used to differentiate if the Activity has been paused by theOperating System (ex: orientation change) or by the user (ex: back button click).
    • Beginners Guide 120 Basic4AndroidProgram flow: Example: MyFirstProgram. 1. The program calls Process_Gloabls. In the example there is no code. 2. Then the program calls Globals. Declares the variables. 3. Then the program calls Activity_Create. Loads the "Main" layout. Calls the New subroutine. 4. The code in Sub New is executed. When reaching End Sub, the program goes back to the line following New. In this case line 25. 5. Activity_Resume is called. No code. 6. The program waits for an event. 7. If the user clicks on the Button btnAction The btnAction_Click Sub is called and the code inside the Sub is executed. 8. The program waits for another event.
    • Basic4Android 121 Beginners guide13.2 ExpressionsAn expression in a programming language is a combination of explicit values, constants, variables,operators, and functions that are interpreted according to the particular rules of precedence and ofassociation for a particular programming language, which computes and then produces (returns)another value. This process, like for mathematical expressions, is called evaluation. The value canbe of various types, such as numerical, string, and logical (source Wikipedia).For example, 2 + 3 is an arithmetic and programming expression which evaluates to 5. A variable isan expression because it is a pointer to a value in memory, so y + 6 is an expression. An example ofa relational expression is 4 = 4 which evaluates to True (source Wikipedia).13.2.1 Mathematical expressions Operator Example Precedence level Operation + x + y 3 Addition - x - y 3 Subtraction * x * y 2 Multiplication / x / y 2 Division Mod x Mod y 2 Modulo y Power Power(x,y) x 1 Power ofPrecedence level: In an expression, operations with level 1 are evaluated before operations withlevel 2, which are evaluated before operations with level 3.Examples:4 + 5 * 3 + 2 = 21 > 4 + 15 + 2(4 + 5) * (3 + 2) = 45 > 9*5(4 + 5)2 * (3 + 2) = 405 > 92 * 5 > 81 * 5Power(4+5,2)*(3+2)11 Mod 4 = 3 > Mod is the remainder of 10 / 4233 Power(23,3) > 23 at the power of 3 - 22 = - 4 (-2)2 = 4
    • Beginners Guide 122 Basic4Android13.2.2 Relational expressionsIn computer science in relational expressions an operator tests some kind of relation between twoentities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 >= 3).In B4A these operators return True or False, depending on whether the conditional relationshipbetween the two operands holds or not (source Wikipedia). Operator Example Used to test = x=y the equivalence of two values <> x <> y the negated equivalence of two values > x>y if the value of the left expression is greater than that of the right < x<y if the value of the left expression is less than that of the right >= x >= y if the value of the left expression is greater than or equal to that of the right <= x <= y if the value of the left expression is less than or equal to that of the right13.2.3 Boolean expressionsIn computer science, a Boolean expression is an expression that produces a Boolean value whenevaluated, i.e. one of True or False. A Boolean expression may be composed of a combination ofthe Boolean constants True or False, Boolean-typed variables, Boolean-valued operators, andBoolean-valued functions (source Wikipedia).Boolean operators are used in conditional statements such as IF-Then and Select-Case. Operator Comment Or Boolean Or Z = X Or Y Z = True if X or Y is equal to True or both are True And Boolean And Z = X And Y Z = True if X and Y are both equal to True Not ( ) Boolean Not X = True Y = Not(X) > Y = False Or And X Y Z Z False False False False True False True False False True True False True True True True13.3 Conditional statementsDifferent conditional statements are available in Basic.
    • Basic4Android 123 Beginners guide13.3.1 If – Then – End IfThe If-Then-Else structure allows to operate conditional tests and execute different code sectionsaccording to the test result.General case:The If-Then-Else structure works as follows: 1. When reaching the line with the If keyword, test1 is executed. 2. If the test result is True, then code1 is executed until the line with the Else If keyword. And jumps to the line following the End If keyword and continues. 3. If the result is False, then test2 is executed. 4. If the test result is True, then code2 is executed until the line with the Else keyword. And jumps to the line following the End If keyword and continues. 5. If the result is False, then code3 is executed and continues at the line following the End If keyword.The tests can be any kind of conditional test with two possibilities True or False.Some examples: The simplest If-Then structure. The same but in one line. The simplest If-Then-Else structure. The same but in one line.Personally, I prefer the structure on several lines, better readable.Old habit from HP Basic some decades ago, this Basic accepted only one instruction per line.Note. Difference between: B4A VB Else If ElseIfIn B4A there is a blanc character between Else and If.
    • Beginners Guide 124 Basic4Android13.3.2 Select – CaseThe Select - Case structure allows to compare a TestExpression to other Expressions anexecute different code sections according to the matches between the TestExpression andExpressions.General case: TestExpression is the expression to test. ExpressionList1 is a list of expressions to compare to TestExpression ExpressionList2 is another list of expressions to compare to TestExpressionThe Select - Case structure works as follows: 1. The TestExpression is evaluated. 2. If one element in the ExpressionList1 matches TestExpression then executes code1 and continues at the line following the End Select keyword. 3. If one element in the ExpressionList2 matches TestExpression then executes code2 and continues at the line following the End Select keyword. 4. For no expression matches TestExpression executes code3 and continues at the line following the End Select keyword.TestExpression can be any expression or value.ExpressionList1 is a list of any expressions or values.Examples: The Value variable is a numeric value. The TestExpression is the sum of a + b The TestExpression is a character at
    • Basic4Android 125 Beginners guideNote. Differences between: B4A VB Select Select Case Case 1,2,3,4,8,9,10 Case 1 To 4 , 8 To 9In VB the keyword Case is added after the Select keyword.VB accepts Case 1 To 4 , this is not implemented in B4A.
    • Beginners Guide 126 Basic4Android13.4 Loop structuresDifferent loop structures are available in Basic.13.4.1 For – NextThe For–Next loop allows to repeat a certain number of times the same code.Example: i incremental variable n1 initial value n2 final value n3 stepThe For–Next loop works like follows: 1. At the beginning, the incremental variable i is equal to the initial value n1. i = n1 2. The specific code between the For and Next keywords is executed. 3. When reaching Next, the incremental variable i is incremented by the step value n3. i = i + n3. 4. The program jumps back to For, compares if the incremental variable i is lower or equal to the final value n2. test if i <= n2 5. If Yes, the program continues at step 2, the line following the For keyword. 6. If No, the program continues at the line following the Next keyword.If the step value is equal to +1 the step keyword is not needed. is the same asThe step variable can be negative.It is possible to exit a For – Next loop with the Exit keyword. In this example, if the variable a equals 0 Then exit the loop.
    • Basic4Android 127 Beginners guideNote: Differences between B4A VB Next Next i Exit Exit ForIn VB the incremantal character is added after the Next Keyword.In VB the loop type is specified after the Exit keyword.13.4.2 Do - LoopSeveral configurations do exist: test is any expression Executes the code while test is True test is any expression Executes the code until test is TrueThe Do While -Loop loop works like follows: 1. At the beginning, test is evaluated. 2. If True, then executes code 3. If False continues at the line following the Loop keyword.The Do Until -Loop loop works like follows: 1. At the beginning, test is evaluated. 2. If False, then executes code 3. If True continues at the line following the Loop keyword.It is possible to exit a Do-Loop structure with the Exit keyword. If a = 0 then exit the loopExamples:Note: Difference between: B4A VB Exit Exit LoopIn VB the loop type is specified after the Exit keyword.VB accepts also following loops, which are not supported inB4A.
    • Beginners Guide 128 Basic4Android13.5 SubsA Subroutine (“Sub”) is a piece of code. It can be any length, and it has a distinctive nameand a defined scope (in the means of variables scope discussed earlier). A Subroutine iscalled “Sub” in Basci4Android code, and is equivalent to procedures, functions, methods andsubs in other programming languages. The lines of code inside a Sub are executed fromfirst to last, as described in the program flow chapter.It is not recommended to have too long Subs, they get less readable.13.5.1 DeclaringA Sub is declared in the following way:It starts with the keyword Sub, followed by the Sub’s name, followed by a parameter list, followedby the return type and ends with the keywords End Sub.Subs are always declared at the top level of the module – that is, you cannot nest two Subsone inside the other.13.5.2 Calling a SubWhen you want the lines of code in a Sub to execute, you simply write the Sub’s name.For example:Interest Value returned by the Sub.CalcInterest Sub name.1235 Capital value transmitted to the Sub.5.25 Rate value transmitted to the Sub.13.5.3 NamingBasically, you can name a Sub any name that’s legal for a variable. It is recommended toname the Sub with a significant name, like CalcInterest in the example, so you can tell what itdoes from reading the code.There is no limit on the number of Subs you can add to your program, but it is notallowed to have two Subs with the same name in the same module.
    • Basic4Android 129 Beginners guide13.5.4 ParametersParameters can be transmitted to the Sub, this list follows the sub name between brackets.The parameter types can be declared in the directly in the list.In B4A, the parameters are transmitted by value and not by reference.13.5.5 Returned valueA sub can return a value, this can be any object.Returning a value is done with the Return keyword.The type of the return value is added after the parameter list.
    • Beginners Guide 130 Basic4Android13.6 LibrariesLibraries add more objects and functionalities to B4A.Some of these libraries are shipped with B4A and are part of the standard development system.Other, often developed by users like Andrew Graham (agraham), can be downloaded (by registeredusers only) to add supplementary functionalities to the B4A development environment.When you need a library, you have to: - Check in the Lib Tab, if you already have the library. - For additional libraries, check if its the latest version. - If yes, then check the library in the list to select it. - If no, download the library, unzip it and copy the <LibraryName>.jar and <LibraryName>.xml files to the additional libraries folder. - Restart the IDE and check the library in the Lib Tab list to select it.13.6.1 Standard librariesThe standard B4A libraries are saved in the Libraries folder in the B4A program folder.Normally in: C:Program FilesAnywhere SoftwareBasic4androidLibraries13.6.2 Additional libraries folderFor the additional libraries it is useful to setup a special folder to save them somewhere else.For example: D:Basic4AndroidAddLibrariesWhen you install a new version of B4A, all standard libraries are automatically updated, but theadditional libraries are not included. The advantage of the special folder is that you dont need tocare about them because this folder is not affected when you install the new version of B4A.The additional libraries are not systematically updated with new version of B4A.When the IDE starts, it looks first for the available libraries in the Libraries folder of B4A and thenin the folder for the additional libraries.
    • Basic4Android 131 Beginners guideIf you setup a special additional libraries folder you must specify it in the IDE.In the menu Tools / Configure Paths:Enter the folder name and click on .13.6.3 Error message "Are you missing a library reference?"If you get this message, means that you forgot to check the specified library in the Lib Tab list !
    • Beginners Guide 132 Basic4AndroidString manipulationTimers
    • Basic4Android 133 Beginners guide14 B4A KeywordsList of types:BitDateTimeExceptionKeywordsLayoutValuesStringStringBuilderTimer14.1 BitBit is a predefined object containing bitwise related methods.Example:Dim flags As Intflags = Bit.Or(100, 200)Events:NoneMembers: And (N1 As Int, N2 As Int) As Int Not (N As Int) As Int Or (N1 As Int, N2 As Int) As Int ParseInt (Value As String, Radix As Int) As Int ShiftLeft (N As Int, Shift As Int) As Int ShiftRight (N As Int, Shift As Int) As Int ToBinaryString (N As Int) As String ToHexString (N As Int) As String ToOctalString (N As Int) As String UnsignedShiftRight (N As Int, Shift As Int) As Int Xor (N1 As Int, N2 As Int) As IntMembers description: And (N1 As Int, N2 As Int) As Int
    • Beginners Guide 134 Basic4AndroidReturns the bitwise AND of the two values. Not (N As Int) As IntReturns the bitwise complement of the given value. Or (N1 As Int, N2 As Int) As IntReturns the bitwise OR of the two values. ParseInt (Value As String, Radix As Int) As IntParses Value as an integer using the specified radix.Radix - Should be between 2 to 36. ShiftLeft (N As Int, Shift As Int) As IntShifts N left.Shift - Number of positions to shift. ShiftRight (N As Int, Shift As Int) As IntShifts N right.Keeps the original value signShift - Number of positions to shift. ToBinaryString (N As Int) As StringReturns a string representation of N in base 2. ToHexString (N As Int) As StringReturns a string representation of N in base 16. ToOctalString (N As Int) As StringReturns a string representation of N in base 8. UnsignedShiftRight (N As Int, Shift As Int) As IntShifts N right.Shifts zeroes in the leftmost positions.Shift - Number of positions to shift. Xor (N1 As Int, N2 As Int) As IntReturns the bitwise XOR of the two values.14.2 DateTimeDate and time related methods.DateTime is a predefined object. You should not declare it yourself.Date and time values are stored as ticks. Ticks are the number of milliseconds since January 1,1970.This value is too large to be stored in an Int variable. It should only be stored in a Longvariable.The methods DateTime.Date and DateTime.Time convert the ticks value to a string.You can get the current time with DateTime.Now.
    • Basic4Android 135 Beginners guideExample:Dim now As Longnow = DateTime.NowMsgbox("The date is: " & DateTime.Date(now) & CRLF & _ "The time is: " & DateTime.Time(now), "")Events:NoneMembers: Add (Ticks As Long, Years As Int, Months As Int, Days As Int) As Long Date (Ticks As Long) As String DateFormat As String DateParse (Date As String) As Long GetDayOfMonth (Ticks As Long) As Int GetDayOfWeek (Ticks As Long) As Int GetDayOfYear (Ticks As Long) As Int GetHour (Ticks As Long) As Int GetMinute (Ticks As Long) As Int GetMonth (Ticks As Long) As Int GetSecond (Ticks As Long) As Int GetYear (Ticks As Long) As Int Now As Long [read only] TicksPerDay As Long TicksPerHour As Long TicksPerMinute As Long TicksPerSecond As Long Time (Ticks As Long) As String TimeFormat As String TimeParse (Time As String) As LongMembers description:
    • Beginners Guide 136 Basic4Android Add (Ticks As Long, Years As Int, Months As Int, Days As Int) As LongReturns a ticks value which is the result of adding the specified time spans to the given ticks value.Pass negative values if you want to subtract the values.Example:Dim Tomorrow As LongTomorrow = DateTime.Add(DateTime.Now, 0, 0, 1)Log("Tomorrow date is: " & DateTime.Date(Tomorrow)) Date (Ticks As Long) As StringReturns a string representation of the date (which is stored as ticks).The date format can be set with the DateFormat keyword.Example:Log("Today is: " & DateTime.Date(DateTime.Now)) DateFormat As StringGets or sets the format used to parse date strings.See this page for the supported patterns: formats.The default pattern is MM/dd/yyyy (04/23/2002 for example). DateParse (Date As String) As LongParses the given date string and returns its ticks representation.An exception will be thrown if parsing fails.Example:Dim SomeTime As LongSomeTime = DateTime.DateParse("02/23/2007") GetDayOfMonth (Ticks As Long) As IntReturns the day of month component from the ticks value.Values are between 1 to 31. GetDayOfWeek (Ticks As Long) As IntReturns the day of week component from the ticks value.Values are between 1 to 7. GetDayOfYear (Ticks As Long) As IntReturns the day of year component from the ticks value.Values are between 1 to 366. GetHour (Ticks As Long) As IntReturns the hour of day component from the ticks value.Values are between 0 to 23. GetMinute (Ticks As Long) As IntReturns the minutes within a hour component from the ticks value.Values are between 0 to 59. GetMonth (Ticks As Long) As Int
    • Basic4Android 137 Beginners guideReturns the month of year component from the ticks value.Values are between 1 to 12. GetSecond (Ticks As Long) As IntReturns the seconds within a minute component from the ticks value.Values are between 0 to 59. GetYear (Ticks As Long) As IntReturns the year component from the ticks value. Now As Long [read only]Gets the current time as ticks (number of milliseconds since January 1, 1970). TicksPerDay As Long TicksPerHour As Long TicksPerMinute As Long TicksPerSecond As Long Time (Ticks As Long) As StringReturns a string representation of the time (which is stored as ticks).The time format can be set with the TimeFormat keyword.Example:Log("The time now is: " & DateTime.Date(DateTime.Now)) TimeFormat As StringGets or sets the format used to parse time strings.See this page for the supported patterns: formats.The default pattern is HH:mm:ss (23:45:12 for example). TimeParse (Time As String) As LongParses the given date string and returns its ticks representation.Note that the returned value date will be today.14.3 ExceptionHolds a thrown exception.You can access the last thrown exception by calling LastException.For example:TryDim in As InputStreamin = File.OpenInput(File.DirInternal, "SomeMissingFile.txt")...CatchLog(LastException.Message)End TryIf in.IsInitialized Then in.Close
    • Beginners Guide 138 Basic4AndroidEvents:NoneMembers: IsInitialized As Boolean Message As String [read only]Members description: IsInitialized As Boolean Message As String [read only]14.4 KeywordsThese are the internal keywords.Events:NoneMembers: Abs (Number As Double) As Double ACos (Value As Double) As Double ACosD (Value As Double) As Double Array Asc (Char As Char) As Int ASin (Value As Double) As Double ASinD (Value As Double) As Double ATan (Value As Double) As Double ATanD (Value As Double) As Double BytesToString (Data() As Byte, StartOffset As Int, Length As Int, CharSet As String) As String Catch cE As Double CharsToString (Chars() As Char, StartOffset As Int, Length As Int) As String Chr (UnicodeValue As Int) As Char
    • Basic4Android 139 Beginners guide Continue Cos (Radians As Double) As Double CosD (Degrees As Double) As Double cPI As Double CRLF As String Density As Float Dim DipToCurrent (Length As Int) As Int DoEvents Exit ExitApplication False As Boolean File As File Floor (Number As Double) As Double For GetDeviceLayoutValues As LayoutValues GetType (object As Object) As String If InputList (Items As List, Title As String, CheckedItem As Int) As Int InputMultiList (Items As List, Title As String) As List Is IsBackgroundTaskRunning (ContainerObject As Object, TaskId As Int) As Boolean IsNumber (Text As String) As Boolean LastException As Exception LoadBitmap (Dir As String, FileName As String) As Bitmap LoadBitmapSample (Dir As String, FileName As String, MaxWidth As Int, MaxHeight As
    • Beginners Guide 140 Basic4AndroidInt) As Bitmap Log (Message As String) Logarithm (Number As Double, Base As Double) As Double Max (Number1 As Double, Number2 As Double) As Double Min (Number1 As Double, Number2 As Double) As Double Msgbox (Message As String, Title As String) Msgbox2 (Message As String, Title As String, Positive As String, Cancel As String, NegativeAs String, Icon As android.graphics.Bitmap) As Int Not (Value As Boolean) As Boolean Null As Object NumberFormat (Number As Double, MinimumIntegers As Int, MaximumFractions As Int) AsString NumberFormat2 (Number As Double, MinimumIntegers As Int, MaximumFractions As Int,MinimumFractions As Int, GroupingUsed As Boolean) As String PerXToCurrent (Percentage As Float) As Int PerYToCurrent (Percentage As Float) As Int Power (Base As Double, Exponent As Double) As Double ProgressDialogHide ProgressDialogShow (Text As String) ProgressDialogShow2 (Text As String, Cancelable As Boolean) QUOTE As String Regex As Regex Return Rnd (Min As Int, Max As Int) As Int Round (Number As Double) As Long Round2 (Number As Double, DecimalPlaces As Int) As Double Select Sender As Object
    • Basic4Android 141 Beginners guide Sin (Radians As Double) As Double SinD (Degrees As Double) As Double Sqrt (Value As Double) As Double StartActivity (Activity As Object) Sub TAB As String Tan (Radians As Double) As Double TanD (Degrees As Double) As Double ToastMessageShow (Message As String, LongDuration As Boolean) True As Boolean Try Type Until WhileMembers description: Abs (Number As Double) As DoubleReturns the absolute value. ACos (Value As Double) As DoubleReturns the angle measured with radians. ACosD (Value As Double) As DoubleReturns the angle measured with degrees. ArrayCreates a single dimension array of the specified type.The syntax is: Array As type (list of values).Example:Dim Days() As StringDays = Array As String("Sunday", "Monday", ...) Asc (Char As Char) As IntReturns the unicode code point of the given character or first character in string.
    • Beginners Guide 142 Basic4Android ASin (Value As Double) As DoubleReturns the angle measured with radians. ASinD (Value As Double) As DoubleReturns the angle measured with degrees. ATan (Value As Double) As DoubleReturns the angle measured with radians. ATanD (Value As Double) As DoubleReturns the angle measured with degrees. BytesToString (Data() As Byte, StartOffset As Int, Length As Int, CharSet As String) AsStringDecodes the given bytes arrays as a string.Data - The bytes array.StartOffset - The first byte to read.Length - Number of bytes to read.CharSet - The name of the character set.Example:Dim s As Strings = BytesToString(Buffer, 0, Buffer.Length, "UTF-8") CatchAny exception thrown inside a try block will be caught in the catch block.Call LastException to get the caught exception.Syntax:Try...Catch...End Try cE As Doublee (natural logarithm base) constant. CharsToString (Chars() As Char, StartOffset As Int, Length As Int) As StringCreates a new String by copying the characters from the array.Copying starts from StartOffset and the number of characters copied equals to Length. Chr (UnicodeValue As Int) As CharReturns the character that is represented by the given unicode value. ContinueStops executing the current iteration and continues with the next one. Cos (Radians As Double) As Double
    • Basic4Android 143 Beginners guideCalculated the trigonometric cosine function. Angle measured in radians. CosD (Degrees As Double) As DoubleCalculated the trigonometric cosine function. Angle measured in degrees. cPI As DoublePI constant. CRLF As StringNew line character. The value of Chr(13). Density As FloatReturns the device scale, which is DPI / 160.(DPI stands for dots per inch). DimDeclares a variable.Syntax:Declare a single variable:Dim variable name [As type]The default type is String.Declare multiple variables. All variables will be of the specified type.Dim variable1, variable2, ..., [As type]Note that the shorthand syntax only applies to Dim keyword.Declare an array:Dim variable(Rank1, Rank2, ...) [As type]Example:Dim Days(7) As StringThe actual rank can be omitted for zero length arrays. DipToCurrent (Length As Int) As IntScales the value, which represents a specific length on a default density device (Density = 1.0),to the current device.For example, the following code will set the width value of this button to be the same physical sizeon all devices.Button1.Width = DipToCurrent(100)Note that a shorthand syntax for this method is available. Any number followed by the string dipwill be converted in the same manner (no spaces are allowed between the number and dip).So the previous code is equivalent to:Button1.Width = 100dip dip -> density independent pixel DoEventsProcesses waiting messages in the messages queue.DoEvents can be called inside lengthy loops to allow the program to process waiting events. ExitExits the most inner loop.
    • Beginners Guide 144 Basic4Android ExitApplicationImmediately ends the application and stops the process.Most applications should not use this method and prefer Activity.Finish which lets the OS decidewhen the process is killed. False As Boolean File As FileFiles related methods. Floor (Number As Double) As DoubleReturns the largest double that is smaller or equal to the specified number and is equal to an integer. ForSyntax:For variable = value1 To value2 [Step interval]...NextExample:For i = 1 To 10Log(i) Will print 1 to 10 (inclusive).NextIf the iterator variable was not declared before it will be of type Int. GetDeviceLayoutValues As LayoutValuesReturns the device LayoutValues.Example:Log(GetDeviceLayoutValues) GetType (object As Object) As StringReturns a string representing the objects java type. IfSingle line:If condition Then true-statement [Else false-statement]Multiline:If condition ThenstatementElse If condition Thenstatement...ElsestatementEnd If InputList (Items As List, Title As String, CheckedItem As Int) As IntShows a modal dialog with a list of items and radio buttons. Pressing on an item will close thedialog.
    • Basic4Android 145 Beginners guideReturns the index of the selected item or DialogResponse.Cancel if the user pressed on the backkey.List - Items to display.Title - Dialog title.CheckedItem - The index of the item that will first be selected. Pass -1 if no item should bepreselected. InputMultiList (Items As List, Title As String) As ListShows a modal dialog with a list of items and checkboxes. The user can select multiple items.The dialog is closed by pressing on the "Ok" button.Returns a list with the indices of the selected items. The list is sorted.Returns an empty list if the user has pressed on the back key. IsTests whether the object if of the given type.Example:For i = 0 To Activity.NumberOfViews - 1If Activity.GetView(i) Is Button ThenDim b As Buttonb = Activity.GetView(i)b.Color = Colors.BlueEnd IfNext IsBackgroundTaskRunning (ContainerObject As Object, TaskId As Int) As BooleanTests whether a background task, submitted by the container object and with the specified id, isrunning. IsNumber (Text As String) As BooleanTests whether the specified string can be safely parsed as a number. LastException As ExceptionReturns the last exception that was caught (if such exists). LoadBitmap (Dir As String, FileName As String) As BitmapLoads the bitmap.Note that the Android file system is case sensitive.You should consider using LoadBitmapSample if the image size is large.The actual file size is not relevant as images are usually stored compressed.Example:Activity.SetBackgroundImage(LoadBitmap(File.DirAssets,"SomeFile.jpg")) LoadBitmapSample (Dir As String, FileName As String, MaxWidth As Int, MaxHeight AsInt) As BitmapLoads the bitmap.The decoder will subsample the bitmap if MaxWidth or MaxHeight are smaller than the bitmapdimensions.This can save a lot of memory when loading large images.Example:
    • Beginners Guide 146 Basic4AndroidActivity.SetBackgroundImage(LoadBitmapSample(File.DirAssets,"SomeFile.jpg", Activity.Width, Activity.Height)) Log (Message As String)Logs a message. The log can be viewed in the LogCat tab. Logarithm (Number As Double, Base As Double) As Double Max (Number1 As Double, Number2 As Double) As DoubleReturns the larger number between the two numbers. Min (Number1 As Double, Number2 As Double) As DoubleReturns the smaller number between the two numbers. Msgbox (Message As String, Title As String)Shows a modal message box with the specified message and title.The dialog will show one OK button.Example:Msgbox("Hello world", "This is the title") Msgbox2 (Message As String, Title As String, Positive As String, Cancel As String,Negative As String, Icon As android.graphics.Bitmap) As IntShows a modal message box with the specified message and title.Message - The dialog message.Title - The dialog title.Positive - The text to show for the "positive" button. Pass "" if you dont want to show the button.Cancel - The text to show for the "cancel" button. Pass "" if you dont want to show the button.Negative - The text to show for the "negative" button. Pass "" if you dont want to show the button.Icon - A bitmap that will be drawn near the title. Pass Null if you dont want to show an icon.Returns one of the DialogResponse values.Example:Dim result As Intresult = Msgbox2("This is the message", "This is the title","Good", "", "Bad", LoadBitmap(File.DirAssets, "smiley.gif"))If result = DialogResponse.Positive Then ... Not (Value As Boolean) As BooleanInverts the value of the given boolean. Null As Object NumberFormat (Number As Double, MinimumIntegers As Int, MaximumFractions As Int)As StringConverts the specified number to a string.The string will include at least Minimum Integers and at most Maximum Fractions digits.Example:Log(NumberFormat(12345.6789, 0, 2)) "12,345.68"Log(NumberFormat(1, 3 ,0)) "001"
    • Basic4Android 147 Beginners guide NumberFormat2 (Number As Double, MinimumIntegers As Int, MaximumFractions AsInt, MinimumFractions As Int, GroupingUsed As Boolean) As StringConverts the specified number to a string.The string will include at least Minimum Integers, at most Maximum Fractions digits and at leastMinimum Fractions digits.GroupingUsed - Determines whether to group every three integers.Example:Log(NumberFormat2(12345.67, 0, 3, 3, false)) "12345.670" PerXToCurrent (Percentage As Float) As IntReturns the actual size of the given percentage of the activity width.Example:Button1.Width = PerXToCurrent(50) Button1.Width = 50% * Activity.WidthA shorthand syntax for this method is available. Any number followed by the string %xwill be converted in the same manner (no spaces are allowed between the number and %x).So the previous code is equivalent to:Button1.Width = 50%x PerYToCurrent (Percentage As Float) As IntReturns the actual size of the given percentage of the activity height.Example:Button1.Height = PerYToCurrent(50) Button1.Height = 50% * Activity.HeightA shorthand syntax for this method is available. Any number followed by the string %ywill be converted in the same manner (no spaces are allowed between the number and %y).So the previous code is equivalent to:Button1.Height = 50%y Power (Base As Double, Exponent As Double) As DoubleReturns the Base value raised to the Exponent power. ProgressDialogHideHides a visible progress dialog. Does not do anything if no progress dialog is visible. ProgressDialogShow (Text As String)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.The dialog will also be removed if the user presses on the Back key. ProgressDialogShow2 (Text As String, Cancelable As Boolean)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.Cancelable - Whether the user can dismiss the dialog by pressing on the Back key. QUOTE As StringQuote character. The value of Chr(34).
    • Beginners Guide 148 Basic4Android Regex As RegexRegular expressions related methods. ReturnReturns from the current sub and optionally returns the given value.Syntax: Return [value] Rnd (Min As Int, Max As Int) As IntReturns a random integer between Min (inclusive) and Max (exclusive). Round (Number As Double) As LongReturns the closest long number to the given number. Round2 (Number As Double, DecimalPlaces As Int) As DoubleRounds the given number and leaves up to the specified number of fractional digits. SelectCompares a single value to multiple values.Select blocks cannot be nested.Example:Dim value As Intvalue = 7Select value Case 1: Log("One") Case 2, 4, 6, 8: Log("Even") Case 3, 5, 7, 9: Log("Odd larger than one") Case Else Log("Larger than 9")End Select Sender As ObjectReturns the object that raised the event.Only valid while inside the event sub.Example:Sub Button_ClickDim b As Buttonb = Senderb.Text = "Ive been clicked"End Sub Sin (Radians As Double) As DoubleCalculated the trigonometric sine function. Angle measured in radians. SinD (Degrees As Double) As DoubleCalculated the trigonometric sine function. Angle measured in degrees.
    • Basic4Android 149 Beginners guide Sqrt (Value As Double) As DoubleReturns the positive square root. StartActivity (Activity As Object)Starts an activity or brings it to front if it already exists.Activity can be a string with the target activity name or it can be the actual activity.After this call the current activity will be paused and the target activity will be resumed.This method can also be used to send Intents objects to the system.Example: StartActivity (Activity2) SubDeclares a sub with the parameters and return type.Syntax: Sub name [(list of parameters)] [As return-type]Parameters include name and type.The lengths of arrays dimensions should not be included.Example:Sub MySub (FirstName As String, LastName As String, Age As Int,OtherValues() As Double) As Boolean...End SubIn this example OtherValues is a single dimension array.The return type declaration is different than other declarations as the array parenthesis follow thetype and notthe name (which does not exist in this case). TAB As StringTab character. Tan (Radians As Double) As DoubleCalculated the trigonometric tangent function. Angle measured in radians. TanD (Degrees As Double) As DoubleCalculated the trigonometric tangent function. Angle measured in degrees. ToastMessageShow (Message As String, LongDuration As Boolean)Shows a quick little message that goes out automatically.Message - The text message to show.LongDuration - If true then shows the message for a long period, otherwise shows the message for ashort period. True As Boolean TryAny exception thrown inside a try block will be caught in the catch block.Call LastException to get the caught exception.Syntax:Try...Catch
    • Beginners Guide 150 Basic4Android...End Try TypeDeclares a structure.Can only be used inside sub Globals or sub Process_Globals.Syntax:Type type-name (field1, field2, ...)Fields include name and type.Example:Type MyType (Name As String, Items(10) As Int)Dim a, b As MyTypea.Initializea.Items(2) = 123 UntilLoops until the condition is true.Syntax:Do Until condition...Loop WhileLoops while the condition is true.Syntax:Do While condition...Loop14.5 LayoutValuesHolds values related to the display.You can get the values of the the current display by calling GetDeviceLayoutValues.For example:Dim lv As LayoutValueslv = GetDeviceLayoutValuesLog(lv) will print the values to the logActivity.LoadLayout and Panel.LoadLayout return a LayoutValues object with thevalues of thechosen layout variant.Events:NoneMembers: Height As Int Scale As Float toString As String
    • Basic4Android 151 Beginners guide Width As IntMembers description: Height As IntThe display height (pixels). Scale As FloatThe device scale value which is equal to dots per inch / 160. For most devices the value will be 1.0or 1.5 (high resolution). toString As String Width As IntThe display width (pixels).14.6 StringStrings are immutable in Basic4android, which means that you can change the value of a stringvariable but you cannot change the text stored in a string object.So methods like SubString, Trim and ToLowerCase return a new string, they do not change thevalue of the current string.Typical usage:Dim s As Strings = "some text"s = s.Replace("a", "b")You can use StringBuilder if you need a mutable string.Note that string literals are also string objects:Log(" some text ".Trim)Events:NoneMembers: CharAt (Index As Int) As Char CompareTo (Other As String) As Int EndsWith (Suffix As String) As Boolean EqualsIgnoreCase (other As String) As Boolean GetBytes (Charset As String) As Byte() IndexOf (SearchFor As String) As Int IndexOf2 (SearchFor As String, Index As Int) As Int Length As Int
    • Beginners Guide 152 Basic4Android Replace (Target As String, Replacement As String) As String StartsWith (Prefix As String) As Boolean SubString (BeginIndex As Int) As String SubString2 (BeginIndex As Int, EndIndex As Int) As String ToLowerCase As String ToUpperCase As String Trim As StringMembers description: CharAt (Index As Int) As CharReturns the character at the given index. CompareTo (Other As String) As IntLexicographically compares the two strings.Returns a value less than 0 if the current string precedes Other.Returns 0 if both strings are equal.Returns a value larger than 0 if the current string comes after Other.Note that upper case characters precede lower case characters.Examples:"abc".CompareTo("da") < 0"abc".CompareTo("Abc") > 0"abc".CompareTo("abca") < 0 EndsWith (Suffix As String) As BooleanReturns true if this string ends with the given Suffix. EqualsIgnoreCase (other As String) As BooleanReturns true if both strings are equal ignoring their case. GetBytes (Charset As String) As Byte()Encodes the string into a new array of bytes.Example:Dim Data() As ByteData = "Some string".GetBytes("UTF8") IndexOf (SearchFor As String) As IntReturns the index of the first occurrence of SearchFor string in the string.Returns -1 if SearchFor was not found. IndexOf2 (SearchFor As String, Index As Int) As Int
    • Basic4Android 153 Beginners guideReturns the index of the first occurrence of SearchFor string in the string.Starts searching from the given Index.Returns -1 if SearchFor was not found. Length As IntReturns the length of this string. Replace (Target As String, Replacement As String) As StringReturns a new string resulting from the replacement of all the occurrences of Target withReplacement. StartsWith (Prefix As String) As BooleanReturns true if this string starts with the given Prefix. SubString (BeginIndex As Int) As StringReturns a new string which is a substring of the original string.The new string will include the character at BeginIndex and will extend to the end of the string.Example:"012345".SubString(2) returns "2345" SubString2 (BeginIndex As Int, EndIndex As Int) As StringReturns a new string which is a substring of the original string.The new string will include the character at BeginIndex and will extend to the character atEndIndex, not including the last character.Example:"012345".SubString2(2, 4) returns "23" ToLowerCase As StringReturns a new string which is the result of lower casing this string. ToUpperCase As StringReturns a new string which is the result of upper casing this string. Trim As StringReturns a copy of the original string without any leading or trailing white spaces.14.7 StringBuilderStringBuilder is a mutable string, unlike regular strings which are immutable.StringBuilder is especially useful when you need to concatenate many strings.The following code demonstrates the performance boosting of StringBuilder:Dim start As Longstart = DateTime.NowRegular stringDim s As StringFor i = 1 To 5000 s = s & i
    • Beginners Guide 154 Basic4AndroidNextLog(DateTime.Now - start)StringBuilderstart = DateTime.NowDim sb As StringBuildersb.InitializeFor i = 1 To 5000 sb.Append(i)NextLog(DateTime.Now - start)Tested on a real device, the first for loop took about 20 seconds and the second took less then tenthof a second.The reason is that the code: s = s & i creates a new string each iteration (strings areimmutable).The method StringBuilder.ToString converts the object to a string.Events:NoneMembers: Append (Text As String) As StringBuilder Initialize Insert (Offset As Int, Text As String) As StringBuilder IsInitialized As Boolean Length As Int [read only] Remove (StartOffset As Int, EndOffset As Int) As StringBuilder ToString As StringMembers description: Append (Text As String) As StringBuilderAppends the specified text at the end.Returns the same object, so you can chain methods.Example:sb.Append("First line").Append(CRLF).Append("Second line") InitializeInitializes the object.Example:Dim sb As StringBuildersb.Initializesb.Append("The value is: ").Append(SomeOtherVariable).Append(CRLF) Insert (Offset As Int, Text As String) As StringBuilder
    • Basic4Android 155 Beginners guideInserts the specified text at the specified offset. IsInitialized As Boolean Length As Int [read only]Returns the number of characters. Remove (StartOffset As Int, EndOffset As Int) As StringBuilderRemoves the specified characters.StartOffset - The first character to remove.EndOffset - The ending index. This character will not be removed. ToString As StringConverts the object to a string.14.8 TimerA Timer object generates ticks events at specified intervals.Using a timer is a good alternative to a long loop, as it allows the UI thread to handle other eventsand messages.Note that the timer events will not fire while the UI thread is busy running other code (unless youcall DoEvents keyword).The timer Enabled property is set to False by default. To make it start working you should change itto True.Timer events will not fire when the activity is paused, or if a blocking dialog (like Msgbox) isvisible.Timers should be declared in Sub Process_Globals. Otherwise you may get multiple timersrunning when the activity is recreated.It is also important to disable the timer when the activity is pausing and then enable it when itresumes. This will save CPU and battery.Events:TickMembers: Enabled As Boolean Initialize (EventName As String, Interval As Long) Interval As LongMembers description: Enabled As BooleanGets or sets whether the timer is enabled (ticking). Initialize (EventName As String, Interval As Long)Initializes the timer with the event sub prefix and the specified interval (measured in milliseconds).IMPORTANT: this object should be declared in Sub Process_Globals.
    • Beginners Guide 156 Basic4AndroidExample:Timer1.Initialize("Timer1", 1000)Timer1.Enabled = TrueSub Timer1_TickHandle tick eventsEnd Sub Interval As LongGets or sets the interval between tick events, measured in milliseconds.
    • Basic4Android 157 Beginners guide15 ViewsList of types:ActivityButtonCheckBoxEditTextImageViewLabelListViewPanelProgressBarRadioButtonScrollViewSeekBarSpinnerTabHostToggleButtonViewWebView15.1 ActivityEach activity module include a predefined Activity object.Activity is the main component of your application.Activities have three special life cycle related event: Activity_Create, Activity_Resume andActivity_Pause.See this tutorial for more information about activities and processes life cycle: Life cycle tutorial.You can add and remove views to this activity with AddView and RemoveViewAt methods.You can also load a layout file with LoadLayout.The Touch event can be used to handle user touches.The first parameter of this event is the Action parameter. The parameter values can beACTION_DOWN,ACTION_MOVE or ACTION_UP. Use this value to find the user current action.The KeyPress event occurs when the user has pressed on the key and assuming that no other viewhas consumed this event (like EditText).When handling the KeyPress event you should return a boolean value which tells whether the keypress event was consumed.For example if the user pressed on the Back key and you return True then the OS will not close youractivity.Sub Activity_KeyPress (KeyCode As Int) As Boolean If Keycode = KeyCodes.KEYCODE_BACK Then Return True Else Return False End IfEnd SubYou can add menu items to the activity with AddMenuItem method. Note that this method should
    • Beginners Guide 158 Basic4Androidonly be called insideActivity_Create event.Events:Touch (Action As Int, X As Float, Y As Float)KeyPress (KeyCode As Int) As Boolean return true if you want to consume the eventClickLongClickMembers: ACTION_DOWN As Int ACTION_MOVE As Int ACTION_UP As Int AddMenuItem (Title As String, EventName As String) AddMenuItem2 (Title As String, EventName As String, Bitmap As android.graphics.Bitmap) AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As Int) Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Finish GetView (Index As Int) As View Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int LoadLayout (Layout As String) As LayoutValues NumberOfViews As Int [read only] RemoveView
    • Basic4Android 159 Beginners guide RemoveViewAt (Index As Int) RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Title As CharSequence Top As Int Width As IntMembers description: ACTION_DOWN As Int ACTION_MOVE As Int ACTION_UP As Int AddMenuItem (Title As String, EventName As String)Adds a menu item to the activity.Title - Menu item title.EventName - The prefix name of the sub that will handle the click event.This method should only be called inside sub Activity_Create.Note that the Sender value inside the click event equals to the clicked menu item text.Example:Activity.AddMenuItem("Open File", "OpenFile")...Sub OpenFile_Click...End Sub AddMenuItem2 (Title As String, EventName As String, Bitmap Asandroid.graphics.Bitmap)Adds a menu item to the activity.Title - Menu item title.EventName - The prefix name of the sub that will handle the click event.Bitmap - Bitmap to draw as the item background.Only the first five (or six if there are six total) menu items display icons.This method should only be called inside sub Activity_Create.Note that the Sender value inside the click event equals to the clicked menu item text.Example:Activity.AddMenuItem2("Open File", "OpenFile",LoadBitmap(File.DirAssets, "SomeImage.png"))
    • Beginners Guide 160 Basic4Android...Sub OpenFile_Click...End Sub AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height AsInt)Adds a view to this activity. Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. FinishCloses this activity. GetView (Index As Int) As ViewGets the view that is stored in the specified index. Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int
    • Basic4Android 161 Beginners guide LoadLayout (Layout As String) As LayoutValuesLoads a layout file (.bal).Returns the LayoutValues of the actual layout variant that was loaded. NumberOfViews As Int [read only]Returns the number of child views. RemoveViewRemoves this view from its parent. RemoveViewAt (Index As Int)Removes the view that is stored in the specified index. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Title As CharSequence Top As Int Width As IntGets or sets the views width.15.2 ButtonA Button view.If you change the buttons background you will usually want to use StateListDrawable which allowsyou to set the "default" drawableand the "pressed" drawable.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:
    • Beginners Guide 162 Basic4AndroidDownUpClickLongClickMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface
    • Basic4Android 163 Beginners guide Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As Boolean
    • Beginners Guide 164 Basic4AndroidTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width.15.3 CheckBoxA CheckBox view. Unlike RadioButtons each CheckBox can be checked independently.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:CheckedChange(Checked As Boolean)Members: Background As android.graphics.drawable.Drawable BringToFront Checked As Boolean Color As Int [write only]
    • Basic4Android 165 Beginners guide Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front.
    • Beginners Guide 166 Basic4Android Checked As Boolean Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As Object
    • Basic4Android 167 Beginners guideGets or sets the Tag value. This is a place holder which can used to store additional data. Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width.15.4 EditTextEditText view is a view that allows the user to write free text (similar to WinForms TextBox).The EditText has two modes; SingleLine and MultiLine. You can set it to be multiline by callingEditText1.SingleLine = FalseOn most devices the soft keyboard will show automatically when the user presses on the EditText.You can change the InputType property and change the type of keyboard that appears.For example: EditText1.InputType = EditText1.INPUT_TYPE_NUMBERS will causethe numeric keyboard to appear whenthe user presses on the EditText. Note that it will also cause the EditText to only accept numbers.The TextChanged event fires whenever the text changes and it includes the old and new strings.The EnterPressed event fires when the user presses on the enter key or action key (Done or Next).This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:TextChanged (Old As String, New As String)EnterPressedMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean ForceDoneButton As Boolean [write only]
    • Beginners Guide 168 Basic4Android Gravity As Int Height As Int Hint As String HintColor As Int Initialize (EventName As String) INPUT_TYPE_DECIMAL_NUMBERS As Int INPUT_TYPE_NONE As Int INPUT_TYPE_NUMBERS As Int INPUT_TYPE_PHONE As Int INPUT_TYPE_TEXT As Int InputType As Int Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int PasswordMode As Boolean [write only] RemoveView RequestFocus As Boolean SelectAll SelectionStart As Int SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) SingleLine As Boolean [write only] Tag As Object
    • Basic4Android 169 Beginners guide Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As Int Wrap As Boolean [write only]Members description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean ForceDoneButton As Boolean [write only]By default the OS sets the virtual keyboard action key to display Done or Next according to thespecific layout.You can force it to display Done by setting this value to True.Example:EditText1.ForceDoneButton = True Gravity As Int Height As Int Hint As StringGets or sets the text that will appear when the EditText is empty.Example:EditText1.Hint = "Enter username" HintColor As Int
    • Beginners Guide 170 Basic4AndroidGets or sets the hint text color.Example:EditText1.HintColor = Colors.Gray Initialize (EventName As String) INPUT_TYPE_DECIMAL_NUMBERS As IntNumeric keyboard will be displayed. Numbers, decimal point and minus sign are accepted. INPUT_TYPE_NONE As IntNo keyboard will be displayed. INPUT_TYPE_NUMBERS As IntNumeric keyboard will be displayed. Only numbers are accepted. INPUT_TYPE_PHONE As IntKeyboard will be displayed in phone mode. INPUT_TYPE_TEXT As IntDefault text mode. InputType As IntGets or sets the input type flag. This flag is used to determine the settings of the virtual keyboard.Example:EditText1.InputType = EditText1.INPUT_TYPE_NUMBERS InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int PasswordMode As Boolean [write only]Sets whether the EditText should be in password mode and hide the actual characters.
    • Basic4Android 171 Beginners guide RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SelectAllSelects the entire text. SelectionStart As IntGets or sets the selection start position (or the cursor position).Returns -1 if there is no selection or cursor. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. SingleLine As Boolean [write only]Sets whether the EditText should be in single line mode or multiline mode. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width. Wrap As Boolean [write only]Sets whether the text content will wrap within the EditText bounds. Relevant when the EditText isin multiline mode.Example:EditText1.Wrap = False
    • Beginners Guide 172 Basic4Android15.5 ImageViewA view that shows an image.You can assign a bitmap using the Bitmap property.The Gravity property changes the way the image appears.The two most relevant values are Gravity.FILL (which will cause the image to fill the entire view)and Gravity.CENTER (which will draw the image in the views center).This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ClickLongClickMembers: Background As android.graphics.drawable.Drawable Bitmap As android.graphics.Bitmap BringToFront Color As Int [write only] Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int
    • Basic4Android 173 Beginners guide RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. Bitmap As android.graphics.BitmapGets or sets the bitmap assigned to the ImageView.Example:ImageView1.Bitmap = LoadBitmap(File.DirAssets, "someimage.jpg") BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As IntGets or sets the gravity assigned to the bitmap.Example:ImageView1.Gravity = Gravity.Fill Height As Int Initialize (EventName As String) Invalidate
    • Beginners Guide 174 Basic4AndroidInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.
    • Basic4Android 175 Beginners guide15.6 LabelA Label view that shows read-only text.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ClickLongClickMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Text As String
    • Beginners Guide 176 Basic4Android TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean
    • Basic4Android 177 Beginners guide Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width.
    • Beginners Guide 178 Basic4Android15.7 ListViewListView is a very useful view that can handle large and small lists.The ListView raises two events. ItemClick is raised when an item is clicked and ItemLongClick israised when an item is clicked and held.See the ListView tutorial for more information.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ItemClick (Position As Int, Value As Object)ItemLongClick (Position As Int, Value As Object)Members: AddSingleLine (Text As String) AddSingleLine2 (Text As String, ReturnValue As Object) AddTwoLines (Text1 As String, Text2 As String) AddTwoLines2 (Text1 As String, Text2 As String, ReturnValue As Object) AddTwoLinesAndBitmap (Text1 As String, Text2 As String, Bitmap Asandroid.graphics.Bitmap)
    • Basic4Android 179 Beginners guide AddTwoLinesAndBitmap2 (Text1 As String, Text2 As String, Bitmap Asandroid.graphics.Bitmap, ReturnValue As Object) Background As android.graphics.drawable.Drawable BringToFront Clear Color As Int [write only] Enabled As Boolean FastScrollEnabled As Boolean GetItem (Index As Int) As Object Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveAt (Index As Int) RemoveView RequestFocus As Boolean ScrollingBackgroundColor As Int [write only] SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) SingleLineLayout As SingleLineLayout [read only] Size As Int [read only] Tag As Object Top As Int
    • Beginners Guide 180 Basic4Android TwoLinesAndBitmap As TwoLinesAndBitmapLayout [read only] TwoLinesLayout As TwoLinesLayout [read only] Visible As Boolean Width As IntMembers description: AddSingleLine (Text As String)Adds a single line item.Example:ListView1.AddSingleLine("Sunday") AddSingleLine2 (Text As String, ReturnValue As Object)Adds a single line item.The specified return value will be returned when calling GetItem or in the ItemClick event.Example:ListView1.AddSingleLine2("Sunday", 1) AddTwoLines (Text1 As String, Text2 As String)Adds a two lines item.Example:ListView1.AddTwoLines("This is the first line.", "And this is thesecond") AddTwoLines2 (Text1 As String, Text2 As String, ReturnValue As Object)Adds a two lines item.The specified return value will be returned when calling GetItem or in the ItemClick event. AddTwoLinesAndBitmap (Text1 As String, Text2 As String, Bitmap Asandroid.graphics.Bitmap)Adds a two lines and a bitmap item.Example:ListView1.AddTwoLinesAndBitmap("First line", "Second line",LoadBitmap(File.DirAssets, "SomeImage.png")) AddTwoLinesAndBitmap2 (Text1 As String, Text2 As String, Bitmap Asandroid.graphics.Bitmap, ReturnValue As Object)Adds a two lines and a bitmap item.The specified return value will be returned when calling GetItem or in the ItemClick event. Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front.
    • Basic4Android 181 Beginners guide ClearClears all items from the list. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean FastScrollEnabled As BooleanGets or sets whether the fast scroll icon will appear when the user scrolls the list.The default is false. GetItem (Index As Int) As ObjectReturns the value of the item at the specified position.Returns the "return value" if it was set and if not returns the text of the first line. Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveAt (Index As Int)Removes the item at the specified position. RemoveViewRemoves this view from its parent. RequestFocus As Boolean
    • Beginners Guide 182 Basic4AndroidTries to set the focus to this view.Returns True if the focus was set. ScrollingBackgroundColor As Int [write only]Sets the background color that will be used while scrolling the list.This is an optimization done to make the scrolling smoother.Set to Colors.Transparent if the background behind the list is not solid color.The default is black. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. SingleLineLayout As SingleLineLayout [read only]Returns the layout that is used to show single line items.You can change the layout values to change the appearance of such items.Example:Dim Label1 As LabelLabel1 = ListView1.SingleLineLayout.LabelLabel1.TextSize = 20Label1.TextColor = Colors.Green Size As Int [read only]Returns the number of items stored in the list. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int TwoLinesAndBitmap As TwoLinesAndBitmapLayout [read only]Returns the layout that is used to show two lines and bitmap items.You can change the layout values to change the appearance of such items.For example if you want to remove the second label (in all items with this layout):ListView1.TwoLinesAndBitmap.SecondLabel.Visible = False TwoLinesLayout As TwoLinesLayout [read only]Returns the layout that is used to show two lines items.You can change the layout values to change the appearance of such items.Example:Dim Label1 As LabelLabel1 = ListView1.TwoLinesLayout.SecondLabelLabel1.TextSize = 20Label1.TextColor = Colors.Green
    • Basic4Android 183 Beginners guide Visible As Boolean Width As IntGets or sets the views width.15.8 PanelA Panel is a view that holds other child views.You can add child views programmatically or by loading a layout file.The Panel raises the Touch event. The first parameter of this event is the Action which is one of theActivity action constants.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:Touch (Action As Int, X As Float, Y As Float)ClickLongClickMembers: AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As Int) Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean GetView (Index As Int) As View Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)
    • Beginners Guide 184 Basic4Android IsInitialized As Boolean Left As Int LoadLayout (Layout As String) As LayoutValues NumberOfViews As Int [read only] RemoveView RemoveViewAt (Index As Int) RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Visible As Boolean Width As IntMembers description: AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height AsInt)Adds a view to this panel. Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean GetView (Index As Int) As ViewGets the view that is stored in the specified index.
    • Basic4Android 185 Beginners guide Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int LoadLayout (Layout As String) As LayoutValuesLoads a layout file to this panel. Returns the value of the chosen layout variant. NumberOfViews As Int [read only]Returns the number of child views. RemoveViewRemoves this view from its parent. RemoveViewAt (Index As Int)Removes the view that is stored in the specified index. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As Object
    • Beginners Guide 186 Basic4AndroidGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.15.9 ProgressBarA progress bar view. The Progress property sets the progress value which is between 0 to 100.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:NoneMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int Progress As Int RemoveView RequestFocus As Boolean
    • Basic4Android 187 Beginners guide SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean
    • Beginners Guide 188 Basic4Android Left As Int Progress As IntGets or sets the progress value. RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.15.10 RadioButtonA RadioButton view. Only one RadioButton in a group can be checked. When a differentRadioButton is checked all others willautomatically be unchecked. Grouping is done by adding RadioButtons to the same activity orpanel.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:CheckedChange(Checked As Boolean)Members: Background As android.graphics.drawable.Drawable
    • Basic4Android 189 Beginners guide BringToFront Checked As Boolean Color As Int [write only] Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntMembers description:
    • Beginners Guide 190 Basic4Android Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Checked As Boolean Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back.
    • Basic4Android 191 Beginners guide SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Text As String TextColor As Int TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width.15.11 ScrollViewScrollView is a view that contains other views and allows the user to vertically scroll those views.See the ScrollView tutorial for more information.The ScrollView has an inner panel which actually contains the child views.You can add views by calling: ScrollView1.Panel.AddView(...)This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:
    • Beginners Guide 192 Basic4AndroidNoneMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean FullScroll (Bottom As Boolean) Height As Int Initialize (Height As Int) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int Panel As Panel [read only] RemoveView RequestFocus As Boolean ScrollPosition As Int SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Visible As Boolean Width As IntMembers description:
    • Basic4Android 193 Beginners guide Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean FullScroll (Bottom As Boolean)Scrolls the scroll view to the top or bottom. Height As Int Initialize (Height As Int)Initializes the ScrollView and sets its inner panel height to the given height.You can later change this height by calling ScrollView.Panel.Height.Dim ScrollView1 As ScrollViewScrollView1.Initialize(1000dip) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int Panel As Panel [read only]Returns the panel which you can use to add views to.Example:ScrollView1.Panel.AddView(...)
    • Beginners Guide 194 Basic4Android RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. ScrollPosition As IntGets or sets the scroll position. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.15.12 SeekBarA view that allows the user to set a value by dragging a slider. Similar to WinForms TrackBar.The ValueChanged event is raised whenever the value is changed. The UserChanged parameter canbe used to distinguish between changes done by the user and changes done programmatically.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ValueChanged (Value As Int, UserChanged As Boolean)Members: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only]
    • Basic4Android 195 Beginners guide Enabled As Boolean Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int Max As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Value As Int Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept.
    • Beginners Guide 196 Basic4Android Enabled As Boolean Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int Max As IntGets or sets the maximum allows value. RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Value As Int
    • Basic4Android 197 Beginners guideGets or sets the current value. Visible As Boolean Width As IntGets or sets the views width.15.13 SpinnerA folded list that opens when the user clicks on it and allows the user to choose an item. Similar toWinForms ComboBox.The ItemClick event is raised each time a user presses on an item (even if it is the already selecteditem).This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ItemClick (Position As Int, Value As Object)Members: Add (Item As String) AddAll (List As List) Background As android.graphics.drawable.Drawable BringToFront Clear Color As Int [write only] Enabled As Boolean GetItem (Index As Int) As String Height As Int IndexOf (value As String) As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)
    • Beginners Guide 198 Basic4Android IsInitialized As Boolean Left As Int Prompt As String RemoveAt (Index As Int) RemoveView RequestFocus As Boolean SelectedIndex As Int SelectedItem As String [read only] SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Size As Int [read only] Tag As Object Top As Int Visible As Boolean Width As IntMembers description: Add (Item As String)Adds an item.Example:Spinner1.Add("Sunday") AddAll (List As List)Adds multiple items.Example:Spinner1.AddAll(Array As String("Sunday", "Monday", ...)) Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front.
    • Basic4Android 199 Beginners guide ClearClears all items. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean GetItem (Index As Int) As StringReturns the item at the specified index. Height As Int IndexOf (value As String) As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int Prompt As StringGets or sets the title that will be displayed when the spinner is opened. RemoveAt (Index As Int)Removes the item at the specified index. RemoveViewRemoves this view from its parent. RequestFocus As Boolean
    • Beginners Guide 200 Basic4AndroidTries to set the focus to this view.Returns True if the focus was set. SelectedIndex As IntGets or sets the index of the selected item. Returns -1 if no item is selected. SelectedItem As String [read only]Returns the value of the selected item. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Size As Int [read only]Returns the number of items. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.
    • Basic4Android 201 Beginners guide15.14 TabHostTabHost is a view that contains multiple tab pages. Each tab page contains other child views.See the TabHost tutorial for more information.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:TabChangedClickLongClickMembers: AddTab (Title As String, LayoutFile As String) AddTab2 (Title As String, View As android.view.View) AddTabWithIcon (Title As String, DefaultBitmap As android.graphics.Bitmap,SelectedBitmap As android.graphics.Bitmap, LayoutFile As String) AddTabWithIcon2 (Title As String, DefaultBitmap As android.graphics.Bitmap,SelectedBitmap As android.graphics.Bitmap, View As android.view.View) Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] CurrentTab As Int Enabled As Boolean Height As Int
    • Beginners Guide 202 Basic4Android Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) TabCount As Int [read only] Tag As Object Top As Int Visible As Boolean Width As IntMembers description: AddTab (Title As String, LayoutFile As String)Adds a tab page.Title - The page title.LayoutFile - A layout file describing the page layout.Example:TabHost1.AddTab("Page 1", "page1.bal") AddTab2 (Title As String, View As android.view.View)Adds a tab page.Title - The page title.View - The page content. Usually the view should be a panel containing other views. AddTabWithIcon (Title As String, DefaultBitmap As android.graphics.Bitmap,SelectedBitmap As android.graphics.Bitmap, LayoutFile As String)Adds a tab page. The tab title includes an icon.Title - The page title.DefaultBitmap - The icon that will be drawn when the page is not selected.
    • Basic4Android 203 Beginners guideSelectedBitmap - The icon that will be drawn when the page is selected.LayoutFile - A layout file describing the page layout.Example:Dim bmp1, bmp2 As Bitmapbmp1 = LoadBitmap(File.DirAssets, "ic.png")bmp2 = LoadBitmap(File.DirAssets, "ic_selected.png")TabHost1.AddTabWithIcon("Page 1", bmp1, bmp2,"tabpage1.bal") AddTabWithIcon2 (Title As String, DefaultBitmap As android.graphics.Bitmap,SelectedBitmap As android.graphics.Bitmap, View As android.view.View)Adds a tab page. The tab title includes an icon.Title - The page title.DefaultBitmap - The icon that will be drawn when the page is not selected.SelectedBitmap - The icon that will be drawn when the page is selected.View - The page content. Usually the view should be a panel containing other views. Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. CurrentTab As IntGets or sets the current tab.Example:TabHost1.CurrentTab = (TabHost1.CurrentTab + 1) ModTabHost1.TabCount switch to the next tab. Enabled As Boolean Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)
    • Beginners Guide 204 Basic4AndroidInvalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. TabCount As Int [read only]Returns the number of tab pages. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.
    • Basic4Android 205 Beginners guide15.15 ToggleButtonA ToggleButton view. This view which is similar to a button has two modes: ON and OFF.When the user presses on it, it will change its mode.You can set the text with the TextOn and TextOff properties.This is an Activity Object, it cannot be declared under Sub Process_Globals.Events:CheckedChange(Checked As Boolean)Members: Background As android.graphics.drawable.Drawable BringToFront Checked As Boolean Color As Int [write only] Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap)
    • Beginners Guide 206 Basic4Android SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object TextColor As Int TextOff As String TextOn As String TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Checked As Boolean Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Gravity As Int Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)
    • Basic4Android 207 Beginners guideInvalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. TextColor As Int TextOff As StringGets or sets the text that will appear in the OFF mode. TextOn As StringGets or sets the text that will appear in the ON mode. TextSize As Float Top As Int Typeface As android.graphics.Typeface Visible As Boolean Width As IntGets or sets the views width.
    • Beginners Guide 208 Basic4Android15.16 ViewView is a special type of object. You cannot create new View objects. However all other view typescan be assigned to a view variable.This allows you to access the shared properties of all views.For example this code hides all views of an activity:For i = 0 To Activity.NumberOfViews - 1 Dim v As View v = Activity.GetView(i) v.Visible = FalseNextThis is an Activity Object, it cannot be declared under Sub Process_Globals.Events:ClickLongClickMembers: Background As android.graphics.drawable.Drawable BringToFront Color As Int [write only] Enabled As Boolean Height As Int Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean Left As Int RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object
    • Basic4Android 209 Beginners guide Top As Int Visible As Boolean Width As IntMembers description: Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean Height As Int InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean Left As Int RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set.
    • Beginners Guide 210 Basic4Android SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Visible As Boolean Width As IntGets or sets the views width.15.17 WebViewThe WebView view uses the internal WebKit engine to display Html pages.The page displayed can be an online page loaded with LoadUrl or a Html string loaded withLoadHtml.This is an Activity Object, it cannot be declared under Sub Process_Globals.Permissions:android.permission.INTERNETEvents:NoneMembers: Back Background As android.graphics.drawable.Drawable
    • Basic4Android 211 Beginners guide BringToFront Color As Int [write only] Enabled As Boolean Forward Height As Int Initialize (EventName As String) Invalidate Invalidate2 (Rect As android.graphics.Rect) Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int) IsInitialized As Boolean JavaScriptEnabled As Boolean Left As Int LoadHtml (Html As String) LoadUrl (Url As String) RemoveView RequestFocus As Boolean SendToBack SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int) Tag As Object Top As Int Url As String [read only] Visible As Boolean Width As Int ZoomEnabled As BooleanMembers description:
    • Beginners Guide 212 Basic4Android BackGoes back to the previous Url. Background As android.graphics.drawable.DrawableGets or sets the background drawable. BringToFrontChanges the Z order of this view and brings it to the front. Color As Int [write only]Sets the background of the view to be a ColorDrawable with the given color.If the current background is of type GradientDrawable or ColorDrawable the round corners will bekept. Enabled As Boolean ForwardGoes forward to the next Url. Height As Int Initialize (EventName As String) InvalidateInvalidates the whole view forcing the view to redraw itself.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate2 (Rect As android.graphics.Rect)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. Invalidate3 (Left As Int, Top As Int, Right As Int, Bottom As Int)Invalidates the given rectangle.Redrawing will only happen when the program can process messages. Usually when it finishesrunning the current code. IsInitialized As Boolean JavaScriptEnabled As BooleanGets or sets whether JavaScript is enabled.JavaScript is enabled by default. Left As Int LoadHtml (Html As String)
    • Basic4Android 213 Beginners guideLoads the given Html.Example:WebView1.LoadHtml("<html><body>Hello world!</body></html>")You can use "file:///android_asset" to access files added with the file manager:WebView1.LoadHtml("<html><body><imgsrc=file:///android_asset/someimage.jpg/></body></html>")Note that files added with the file manager should be accessed with a lower cased name. LoadUrl (Url As String)Loads the given Url.Example:WebView1.LoadUrl("http://www.google.com") RemoveViewRemoves this view from its parent. RequestFocus As BooleanTries to set the focus to this view.Returns True if the focus was set. SendToBackChanges the Z order of this view and sends it to the back. SetBackgroundImage (Bitmap As android.graphics.Bitmap) SetLayout (Left As Int, Top As Int, Width As Int, Height As Int)Changes the view position and size. Tag As ObjectGets or sets the Tag value. This is a place holder which can used to store additional data. Top As Int Url As String [read only]Returns the current Url. Visible As Boolean Width As IntGets or sets the views width. ZoomEnabled As BooleanGets or sets whether the internal zoom feature is enabled.The zoom feature is enabled by default.
    • Beginners Guide 214 Basic4Android16 Graphics
    • Basic4Android 215 Beginners guide17 VB6 versus B4AWritten by : nfordbscndrd http://www.basic4ppc.com/forum/members/nfordbscndrd.html VB6 B4A === ===controls Views (button, edittext, label, etc.)In the VB6 code window, the top left drop-down list contains allthe controls you have placed in the current form and the right listcontains all the events for each control. The equivalent in B4A canbe found by clicking on Designer - Tools - Generate Members. Onceyou have created Subs in the program coding window, the tab "Modules"on the right side will list each of the Subs.In B4A, you start by typing "Sub [viewName]" followed by a space andfollow the prompts, pressing Enter after each selection until B4Aends with "EventName" highlighted. This is where you would type inthe name of the Sub.Dim/ReDim:---------Dim Array(n) Dim Array(n+1)While "n" is the last index number in VB6, it indicates the numberof array elements when used in B4A. For example, to Dim an arraywith 0-32 elements in VB6, you would say Dim A(32), while to convertthis to B4A, you need to change it to Dim A(33), yet index #33 isnever used (doing so would cause an out-of-range error).ReDim Array() Dim Array(n+1) -- to clear an array, just Dim it again.[Dim a Int: Dim b as Boolean]If Not b Then... If Not(b) Then...If b Then... sameIf b = True Then sameIf a Then... If a > 0 Then... B4A does not treat any non-zero value as True like VB6.a = a + b If b = True Then a = a - 1 Booleans value cannot be used in a math function in B4A.Global Const x=1 B4A does not have a Global Const function. In Sub Globals, you can say Dim x as Int: x = 1 but x is not a constant (its value can be changed).Loops, If-Then, Select Case:---------------------------Do [Until/While] sameLoop [Until/While] Loop [Until/While not allowed.]For - Next sameFor i... - Next i The loop variable (i) is not allowed with Next.Exit Do/For ExitIf - Then - Else same, except VBs ElseIf is "Else If" in B4A; ditto EndIf --- Continue [Skips to Next in For-Next loop]For i = 1 to 6 For i = 1 to 6 If i = 4 Then If i = 4 Then Continue ...code... ...code... End If ...Next NextSelect Case [expr] Select [value]Colors:
    • Beginners Guide 216 Basic4Android------L1.BackColor = L1.Color = Colors.Red vbRedL1.ForeColor = L1.TextColor = Colors.Black vbBlackCalling a sub:-------------SubName x, y SubName(x, y)Sub SubName() Sub SubName() As Int/String/etc. -- a Global variable cannotbe a parameter, so say that "player" is a Global variable,you cannot say: PlayCard(player). Instead you have to say: i=player: PlayCard(i)Function FName() Sub FName() As [var.type] As [var.type] In B4A, any Sub can be used like a Function by adding a variable type such as Sub CheckX(x As Int) As Boolean ...optional code... If x = [desired value] Then Return True ...optional code... End Sub If no Return is given, then zero/False/"" is returned. The calling code does not have to reference the returned value, so that while "If CheckX(x) = True..." is valid, so is just "CheckX(x)"Exit Sub ReturnExit Function Return [value]General:-------DoEvents same, except that Erel says: "Calling DoEvents in a loop consumes a lot of resources and it doesnt allow the system to process all waiting messages properly." This was in response to my pointing out thatwhile in a Do Loop with DoEvents in it, WebView could not beloaded or if loaded, would not process a hyperlink click. AndAgraham says: "Looping is bad practice on mobile devices. The CPUwill be constantly executing code and using battery power as the code will never get back to the OS idle loop where thehardware power saving measures are invoked."Format() NumberFormat & NumberFormat2 [see documentation]InputBox($) InputList(Items as List, Title, CheckedItem as Int) as Int Shows list of choices with radio buttons. Returns index. CheckedItem is the default. InputMultiList(Items as List, Title) As List Usere can select multiple items via checkboxes. Returns list with the indexes of boxes checked.MsgBox "text" MsgBox("text", "title")i=MsgBox() MsgBox2(Message, Title, Positive, Cancel, Negative, Icon) asInt Displays three buttons with text to display for buttons (Positive, Cancel, Negative) Icon is displayed near the title and is specified like:
    • Basic4Android 217 Beginners guide LoadBitmap(File.DirAssets, "[filename].gif") --- ToastMessageShow(text, b) [where b=True for long duration]Rnd is < 1 Rnd(min, max) is integer >= min to < maxRound(n) same, or Round2(n, x) where x=number of decimal placesi = Val(string) If IsNumber(string) Then i = string Else i = 0 -- An attempt to use i=string "throws an exception" if thestring is not numbers.control.SetFocus view.RequestFocusn / 0 : error n / 0 = 2147483647 -- B4A does not "throw an exception" for division by 0, but it does return 2147483647 no matter what the value of "n" is.x = Shell("...") See "Intent". This is not a complete replacement, but allows code such as the following from the B4A forum (by Erel): Dim pi As PhoneIntents StartActivity(pi.OpenBrowser("file:///sdcard/yourfile.html"))t = Timer t = DateTime.Now Ticks are number of milliseconds since 1-1-70TabIndex:--------In VB6, TabIndex can be set to control the order in which controls get focuswhen Tab is pressed. According to Erel, in B4A: "Android handles the sequence according to their position. You can set EditText.ForceDone = True in all your EditTexts. Then catch the EditText_EnterPressed event and explicitly set the focus to the next view (with EditText.RequestFocus)."Setting Label Transparency:--------------------------Properties - Back Style Designer - Drawable - AlphaConstants:---------"" Quote = Chr$(34)vbCr CRLF = Chr$(13)vbCrLf noneString "Members":----------------VB6 uses a character position pointer starting with 1.B4A uses a character Index pointer starting with 0. VB6 B4AMid$("abcde", 1, 1) = "a" = letter array index 0 -- "a" = "abcde".CharAt(0)Mid$("abcde", 2, 1) = "b" = letter array index 1Mid$("abcde", 3, 1) = "c" = letter array index 2Mid$("abcde", 4, 1) = "d" = letter array index 3Mid$("abcde", 5, 1) = "e" = letter array index 4 VB6 B4A === ===Mid$(text, n, 1) text.CharAt(n-1)Mid$(text, n) text.SubString(n-1)Mid$(text, n, x) [x=length wanted] text.SubString2(n-1, n+x-1) [n+x-1=endposition]
    • Beginners Guide 218 Basic4AndroidMid$(text, n, x) = text2 text = text.SubString2(0, n-2) & _ text2.SubString2(0, x-1) & _ text.SubString(n-1 + z) where... z = Min(x, text2.length)Left$(text, n) [n=num.of chars.] text.SubString2(0, n)Right$(text, n) text.SubString(text.Length - n + 1)If a$ = b$... If a.CompareTo(b)...If Right$(text, n) = text2... If text.EndsWith(text2)...If Left$(text, n) = text2... If text.StartsWith(text2)...If Lcase$(text) = Lcase$(text2)... If text.EqualsIgnoreCase(text2)...x = Len(text) x = text.Lengthtext = Replace(text, str, str2) text.Replace(str, str2)Lcase(text) text.ToLowerCaseUcase(text) text.ToUpperCaseTrim(text) text.Trim (no LTrim or RTrim in B4A)Instr(text, string) text.IndexOf(string)Instr(int, text, string) text.IndexOf2(string, int) Returns -1 if not found. Returns char. index, not position. Starts search at "int".If Lcase$(x) = Lcase$(y)... If x.EqualsIgnoreCase(y)...text = Left$(text, n) & s & text.Insert(n, s) Right$(Text, y)Asc(s) [where s = a character] sameError Trapping:--------------VB6:===Sub SomeSub On [Local] Error GoTo ErrorTrap ...some code... On Error GoTo 0 [optional end to error trapping] ...optional additional code... Exit Sub [to avoid executing ErrorTrap code]ErrorTrap: ...optional code for error correction... Resume [optional: "Resume Next" or "Resume [line label]".End SubB4A:===Sub SomeSub Try ...some code... Catch [only executes if error above] Log(LastException) [optional] ...optional code for error correction... End Try ...optional additional code...End SubWIth B4A, if you get an error caught in the middle of a large subroutine, youcanNOT make a correction and resume within the code you were executing. Only thecodein "Catch" gets executed. That would seem to make Try-Catch-End Try of usemainlyduring development.Try-Catch in place of GoTo:--------------------------Try-Catch can be used as a substitute for GoTo [line label] for forward, but not
    • Basic4Android 219 Beginners guidebackward, jumps. It cannot be used to replace GoSub, for which B4A has noequivalent.Start the code with "Try" and replace the [line label] with "Catch".Replace "GoTo [line label]" with code which will create an exception, whichcausesa jump to "Catch", such as OpenInput("bad path", "bad filename")."Immediate Window" vs "Logs" Tab--------------------------------Comments, variable values, etc., can be displayed in VB6s ImmediateWindow by entering into the code "Debug.Print ...".In the B4A environment, the Logs tab on the right side of the IDE is away to show the values of variables, etc., while the code is running.Both VB6 and (now) B4A allow single-stepping through the code while itis running and viewing the values of variables. VB6 also allows changingthe value of variables, changing the code, jumping to other lines fromthe current line, etc. Because B4A runs on a PC while the app runs ona separate device, B4A is currently unable to duplicate all of theseVB6 debug features.
    • Beginners Guide 220 Basic4Android18 GlossaryAndroid Android is a software stack for mobile devices that includes an operating system,middleware and key applications. Google Inc. purchased the initial developer of the software,Android Inc., in 2005.Java Java is a programming language originally developed by James Gosling at SunMicrosystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a corecomponent of Sun Microsystems Java platform. The language derives much of its syntax from Cand C++ but has a simpler object model and fewer low-level facilities.Activity An activity is a single, focused thing that the user can do. Almost all activitiesinteract with the user, so the Activity class takes care of creating a window for you in which youcan place your UI.View Provides classes that expose basic user interface classes that handle screen layout andinteraction with the user. Examples: Label, Panel, Button, EditText etc.