B4iBeginnersGuideV1 2 PDF
B4iBeginnersGuideV1 2 PDF
1 Getting Started 10
1.1 Installing B4i 10
1.1.1 Installing Java JDK 10
1.1.2 Installing B4i 11
1.1.3 Mac Builder installation 12
1.1.4 Hosted Mac builder service (optional) 13
1.2 Configure Paths in the IDE 14
1.3 Creating a certificate and provisioning profile 15
1.3.1 UDID 15
1.3.2 Certificate and Provisioning Profile 16
1.4 Installing B4i-Bridge and debugging first app 17
1.4.1 Install the B4I certificate 17
1.4.2 Set the package name based on the provision app id 17
1.4.3 Install Build B4i-Bridge 18
1.4.4 Load B4i-Bridge 18
1.4.5 Install B4i-Bridge and run it 19
2 My first program (MyFirstProgram.b4i) 20
3 Second program 43
4 The IDE 57
4.1 Menu and Toolbar 58
4.1.1 Toolbar 58
4.1.2 File menu 59
4.1.3 Edit menu 59
4.1.4 Project menu 60
4.1.5 Tools menu 60
4.1.5.1 IDE Options 61
4.1.5.1.1 Themes 61
4.1.5.1.2 Font Picker 62
4.1.5.1.2.1 Word wrap 62
4.1.5.1.3 Configure Process Timeout 62
4.1.5.1.4 Disable Implicit Auto Completion 62
4.1.5.2 Clean Files Folder (unused files) 63
4.1.5.3 Clean Project 63
4.2 Code area 64
4.2.1 Code header Project Attributes 64
4.2.1.1 #AppFont 65
4.2.1.2 #ApplicationLabel 65
4.2.1.3 #DeviceCapabilities 65
4.2.1.4 #If / #End If 65
4.2.1.5 #Region / #End Region 65
4.2.1.6 #IgnoreWarnings 66
4.2.1.7 #IpadOrientaions / #IPhoneOrientations 66
4.2.1.8 #PlistExtra 66
4.2.1.8.1 Share application files with iTunes 66
4.2.1.8.2 Prevent the application running in the background 66
4.2.1.9 #URLScheme 66
4.2.1.10 #Version 66
4.2.2 Undo – Redo 67
4.2.3 Collapse a subroutine 67
4.2.4 Collapse a Region 68
4.2.5 Collapse the whole code 69
4.2.6 Copy a selected bloc of text 71
Table of contents 3 B4i Beginner’s Guide
Klaus Christl
Erel Uziel
All the source code and files needed (layouts, images etc.) of the example projects in this guide are
included in the SourceCode folder.
1 Getting Started
B4i is a simple yet powerful development environment that targets Apple devices (iPhone, iPad
etc.).
Basic4i language is similar to Visual Basic and B4A language.
Basic4i compiled applications are native iOS applications; there are no extra runtimes or
dependencies.
Unlike other IDE’s, B4i is 100% focused on iOS.
B4i includes a powerful GUI designer, built-in support for multiple screens and orientations.
You can develop and debug with a real device
If you are already using B4A you can skip this chapter.
Installation instructions:
The first step should be to install the Java JDK, as B4i requires it.
Note that there is no problem with having several versions of Java installed on the same computer.
iOS compilation requires an Apple Mac computer. Developers have two options with B4i:
Use a local Mac machine connected over the local network.
For this you should also download the Mac builder and install it.
Use our hosted builder rental service. Hosted Mac Builder installation.
The builder service allows you to develop iOS applications without a Mac computer.
All of the development steps can be done with the builder service except of the final step
which is uploading the application to Apple App Store. This step requires a Mac or a service
such as MacInCloud.
Note that the builder is currently limited to projects of up to 15mb.
Copy the license file b4i-license.txt to the B4i folder and to a safe place on the computer for backup.
Note that this is not a text file, do not open it with a text editor.
When you first run B4i you will be asked to enter your e-mail address, the one you used when you
purchased it B4i.
You find it also in the mail you received with the B4i file.
iOS compilation requires an Apple Mac computer. Developers have two options with B4i:
- Use a local Mac machine connected over the local network.
- Use our hosted builder rental service.
These instructions explain how to install the builder on a local Mac machine.
- By default ports numbers 51041 (http) and 51042 (https) are used.
- The firewall should be either disabled or allow incoming connections on these two ports.
- You can test that the server is running by going to the following link: http://<server ip>:51041/test
- You can kill the server with: http://<server ip>:51041/kill
- It is recommended to set your Mac server ip address to a static address. This can be done in your
router settings or in the Mac under Network settings.
- A single Mac builder can serve multiple developers as long as they are all connected to the same
local network. Note that you are not allowed to host builders for developers outside of your
organization.
Multiple IPs.
When the server is started it takes the first IP address reported by the OS and uses it as its own IP
address. You can see this address in the server messages.
In most cases this is the correct address. However if it is not the correct IP address then the server
will not be usable.
In that case you need to explicitly set the correct address:
- Open the key folder and delete all files.
- Edit key.txt and change it to:
1 Getting Started 13 B4i Beginner's Guide
If you have bought the hosted Mac builder service you got a mail with your user ID.
javac.exe:
Enter the folder of the javac.exe file.
Keys folder:
Create a special folder for the Keys, for example C:\B4i\Keys.
Additional libraries:
Create s specific folder for additional libraries, for example C:\B4i\AdditionalLibraries.
Shared Modules:
Create s specific folder for shared modules, for example C:\B4i\SharedModules.
1 Getting Started 15 B4i Beginner's Guide
Don't panic!
While this process can be a bit annoying it is not too complicated and you can always delete the
keys and start from scratch (which is not always the case in Android).
Note that you must first register with Apple as an iOS developer (costs $99 per year).
The whole process is done on a Windows computer.
In order to install an app on an iOS device you need to create a certificate and a provisioning
profile.
The certificate is used to sign the application. The provisioning profile, which is tied to a specific
certificate, includes a list of devices that this app can be installed on.
The video shows the steps required for creating and downloading a certificate and provisioning
profile.
There are two steps which are not shown in the video and are also required before you can create a
provisioning profile:
- Create an App ID. This step is quite simple. Just make sure that you create a wildcard id.
- Add one or more devices. You will need to find the devices UDID for that.
Link to the tutorial in the forum: Creating a certificate and provisioning profile.
1.3.1 UDID
Devices are recognized by their UDIDs. There are two ways to get the device UDID:
1. If iTunes is installed then you can find it in iTunes.
The first time, connect your device with the USB cable to the computer.
Run iTunes, you should see on top this icon . It can take a while before you see it.
Main steps:
Note that you can choose either iOS App Development or App Store and Ad Hoc in the
certificate page.
4. Create and download a provisioning profile.
1 Getting Started 17 B4i Beginner's Guide
You need to install B4i-Bridge once. It is done from the device browser.
Link to the tutorial in the forum: Installing B4i-Bridge and debugging first app.
Run B4i, load a project or use the default project and set the package name based on the provision
app ID.
In the menu click on .
Example in my case:
1 Getting Started 18 B4i Beginner's Guide
Click on
Close Safari.
Click on this B4i-Bridge icon on the device, you will see the installing animation and
Tips:
- You don't need to wait for the installation animation to complete. Once the animation starts you
can click on the app icon.
- If the installation is stuck in the "waiting" step for more than 10 or 15 seconds then uninstall it and
install it again.
- B4i-Bridge must be in the foreground for it to be able to start an installation or to run the
application. In most cases it will be in the foreground automatically. If it is not in the foreground
then you need to click on it to bring it to the foreground.
2 My first program 20 B4i Beginner's Guide
The project is available in the SourceCode folder shipped with the Beginner’s Guide:
SourceCode\MyFirstProgram\MyFirstProgram.b4i
In iOS:
- Label is an object to show text.
- TextField is an object allowing the user to enter text.
- Button is an object allowing user actions.
We will design the layout of the user interface with the Designer, the Abstract Designer and on a
Device and go step by step through the whole process.
The Designer manages the different objects of the interface.
The AbstractDesigner shows the positions and sizes of the objects and allows moving or resizing
them on the screen.
On the Device we see the real result.
2 My first program 21 B4i Beginner's Guide
The Application label is the name of the program that will be shown on the device.
On top of the code screen you see the ‘region’ Project Attributes.
The other lines are explained in Code header Project Attributes / Activity Attributes.
2 My first program 23 B4i Beginner's Guide
IDE menu / /
Click on .
You will see this screen on the device (only the upper part is shown).
Note that in the bottom left of the Designer window you see the connection status:
With the Designer we have also the Abstract Designer which shows the layout not exactly
WYSIWYG but the positions and size of the different objects.
Only the top of the image is shown.
The dark gray area represents the screen area of the connected device.
2 My first program 26 B4i Beginner's Guide
The label appears in the Abstract Designer, in the Views Tree window and its default properties are
listed in the Properties window.
The new properties Left, Top, Width and Height are directly
updated in the Properties window.
You can also modify the Left, Top, Width and Height
properties directly in the Properties window.
We have now:
Set Left, Top, Width and Height to the values in the picture.
Visible is checked.
Text set to 5
We need a second Label similar to the first one. Instead of adding a new one, we copy the first one
with the same properties. Only the Name and Left properties will change.
In the left part, in the Views Tree, you see the different views.
The new label Label1 is added.
Let us now add a 3rd Label for the math sign. We copy once again lblNumber1.
Right click on lblNumber1 in the Abstract Designer and click on in the popup menu.
Position it between the first two Labels and change its name to lblMathSign, its
Text property to '+'.
Position it below the three Labels and change its name to txfResult.
'txf' means TextField and 'Result' for its purpose.
2 My first program 31 B4i Beginner's Guide
Border Width to 1
Text Size to 30
After making these changes, you should see something like this.
2 My first program 32 B4i Beginner's Guide
Now, let's add the Button which, when pressed, will either check the
result the user supplied as an answer, or will generate a new math
problem, depending on the user's input.
Name to btnAction
Border Width to 1
Text Size to 24
2 My first program 33 B4i Beginner's Guide
Let us add the last Label for the comments. Position it below the
Button and resize it.
Border Width to 1
Text Size to 20
Click on .
2 My first program 35 B4i Beginner's Guide
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.
The Generate Members tool automatically generates references and subroutine frames.
Sub btnAction_Click
End Sub
Click on to generate the references and Sub frames, then close the window .
2 My first program 36 B4i Beginner's Guide
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
iOS needs an Application, a NavigationControl and at least one Page, the details are explained in
the chapter Process life cycle.
Below the code above we have the Application_Start routine which is the first routine called when
the program starts.
The content below is also added automatically in each new project.
First, we need our program to load the layout file we defined in the previous pages.
The file must be loaded onto the RootPanel of Page1, we load it just before
NavControl.ShowPage(Page1)
We take advantage of the autocomplete and in-line help features of B4i.
P is completed to Page1.
Now enter a dot “.”
We see RootPanel highlighted, and besides the list the in-line help with the syntax for the property
and an explanation.
2 My first program 38 B4i Beginner's Guide
Enter “(”.
The yellow line in the left border shows that a modification was made in the code.
As soon as you save the code the yellow line will be changed to a green line.
2 My first program 39 B4i Beginner's Guide
We want to generate a new problem as soon as the program starts. Therefore, we add a call to the
New subroutine in Application_Start.
New
End Sub
New is displayed in red because the ‘New’ routine has not yet been defined.
Generating a new problem means generating two new random values between 1 and 9 (inclusive)
for Number1 and Number2, then showing the values using the lblNumber1 and lblNumber2 ‘Text’
properties.
The following line of code generates a random number from '1' (inclusive) to '10' (exclusive) :
Rnd(1, 10)
In this line Number1 = Rnd(1, 10) ' Generates a random number between 1 and 9
The text after the quote, ' Generates..., is considered as a comment.
It is good practice to add comments explaining the purpose of the code.
If btnAction.Text = "O K" Then checks if the Button text equals "O K"
If yes then we check if the TextField is empty.
If yes, we display a MessageBox telling the user that there is no result in the TextField view.
If no, we check if the result is correct or if it is wrong.
If no then we generate a new problem, set the Button text to "O K" and clear the TextField view.
With If txfResult.Text = Number1 + Number2 Then we check if the entered result is correct.
Touch on .
Then you will see somewhere on the device the icon of
Enter 14
If the result is correct you will see the screen on the left.
3 Second program
The project is available in the SourceCode folder: SourceCode\SecondProgram\SecondProgram.b4i.
Create a new folder called “SecondProgram”. Copy all the files and folders from MyFirstProgram
to the new SecondProgram folder and rename the program file MyFirstProgram.b4i to
SecondProgram.b4i and MyFirstProgram.meta to SecondProgram.meta.
Then we must change the ApplicationLabel on the very top of the code.
#Region Project Attributes
#ApplicationLabel: SecondProgram
Name to lblResult
Boarder Width to 1
Change
Corner radius to 0
3 Second program 47 B4i Beginner's Guide
Click on btnAction.
pnlKeyboard Left = 15
pnlKeyboard Top = 240
pnlKeyboard Width = 290
pnlKeyboard Height = 170
pnlKeyboard BorderWidth = 0
Click on
Name to btn0
Event name to btnEvent
Left to 0
Top to 120
Width to 50
Height to 50
Tag to 0
Background Color to #B7FA7EA9
3 Second program 49 B4i Beginner's Guide
Boarder Width to 1
Corner Radius to 5
Text to 0
Size to 28
Let us duplicate btn0 and position the new one beside button btn0.
Tag to 1
Text to 1
Click on
3 Second program 53 B4i Beginner's Guide
Now we write the routine that handles the Click events of the Buttons.
The Event Name for all buttons, except btnAction, is "btnEvent".
The routine name for the associated click event will be btnEvent_Click.
Enter the following code:
End Sub
We need to know what button raised the event. For this, we use the Sender object which is a special
object that holds the object reference of the view that generated the event in the event routine.
Private Sub btnEvent_Click To have access to the properties of the view that raised the
Dim btnSender As Button event we declare a local variable
Dim btnSender As Button.
btnSender = Sender And set btnSender = Sender.
Select btnSender.Tag
Case "BS"
Case Else
lblResult.Text = lblResult.Text & btnSender.Text
End Select
End Sub
The "&" character means concatenation, so we just append to the already existing text the value of
the Text property of the button that raised the event.
When clicking on the BS button we must remove the last character from the existing text in
lblResult. However, this is only valid if the length of the text is bigger than 0. This is checked with:
If lblResult.Text.Length > 0 Then
btnSender = Sender
Select btnSender.Tag
Case "BS"
If lblResult.Text.Length >0 Then
lblResult.Text = lblResult.Text.SubString2(0,lblResult.Text.Length - 1)
End If
Case Else
lblResult.Text = lblResult.Text & btnSender.Text
End Select
End Sub
In Sub btnAction_Click we add, at the end, lblResult.Text = "" to clear the text.
Else
New
btnAction.Text = "O K"
lblResult.Text = ""
End If
End Sub
3 Second program 55 B4i Beginner's Guide
We can try to improve the user interface of the program by adding some colors
to the lblComments Label.
Let us set:
- Yellow for a new problem
- Light Green for a GOOD answer
- Light Red for a WRONG answer.
And in the CheckResult routine we add the two lines with lblComments.Color =...
And we give the program a more meaningful title by adding Page1.Title = "Calc Trainer" in
Application_Start just before NavControl.ShowPage(Page1).
3 Second program 56 B4i Beginner's Guide
Another improvement would be to hide the '0' button to avoid entering a leading '0'.
For this, we hide the button in the New subroutine with line btn0.Visible = False.
We see that btn0 is in red, this means that this object is not recognized by the IDE.
btn0.Visible = False
In addition, in the btnEvent_Click subroutine, we hide the button if the length of the text in
lblResult is equal to zero and show it if the length is greater than zero.
btnSender = Sender
Select btnSender.Tag
Case "BS"
If lblResult.Text.Length >0 Then
lblResult.Text = lblResult.Text.SubString2(0,lblResult.Text.Length - 1)
End If
Case Else
lblResult.Text = lblResult.Text & Send.Tag
End Select
If lblResult.Text.Length = 0 Then
btn0.Visible = False
Else
btn0.Visible = True
End If
End Sub
4 The IDE 57 B4i Beginner’s Guide
4 The IDE
The Integrated Development Environment.
When you run the IDE you will get a form like the image below:
Tabs area Window showing different data depending on the selected Tab.
4.1.1 Toolbar
The 5 functions below are active only when the debugger is active.
Details in Debugging.
Step In [F8].
Step Over [F9].
Step Out [F10].
Stop.
Restart [F11].
Build Configuration.
4 The IDE 59 B4i Beginner’s Guide
New
Open Source Loads a project.
Save Saves the current project.
Export As Zip
Exports the whole project in a zip file.
Print Preview Shows a print preview.
Print Prints the code.
Exit Leaves the IDE.
IDE Options
B4i Bridge, sets the IP address for connection with Wifi
Build Server
Clean Files Folder (removes unused files)
Clean Project
Configure Paths
Private Sign Key
Color Picker
4 The IDE 61 B4i Beginner’s Guide
Themes
Font Picker
Auto Save Saves the program every time you run it.
Configure Process Timeout
Clear Logs When Deploying Removes all Log statements when compiled in Release mode.
Disable Implicit Auto Completion
4.1.5.1.1 Themes
With word wrap. The end of the line is wrapped to the next line.
If
is unchecked you will see a drop down list
with possible words during typing.
The 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.
'Code module
#Region Project Attributes
#ApplicationLabel: SecondProgram
#Version: 1.0.0
'Orientation possible values: Portrait, LandscapeLeft, LandscapeRight and
PortraitUpsideDown
#iPhoneOrientations: Portrait, LandscapeLeft, LandscapeRight
#iPadOrientations: Portrait, LandscapeLeft, LandscapeRight, PortraitUpsideDown
#End Region
When you want to add a new Attribute you can just write # and the inline help shows all
possibilities.
4 The IDE / 4.2 Code area 65 B4i Beginner's Guide
4.2.1.1 #AppFont
In order to add custom font files to your application you need to follow these instructions:
1. Add the font file to the "special" folder: <project>\Files\Special
2. Add the #AppFont attribute for each font file (including the extension):
#AppFont: papercuts-2.ttf
#AppFont: vermidirouge 1.0.ttf
3. Find the font name. You can double click on the font file:
C:\Windows\Fonts
4. Create a new font with this font name. The name should not include spaces:
Label1.Font = Font.CreateNew2("VermidiRouge", 30)
Label2.Font = Font.CreateNew2("PaperCuts2", 20)
4.2.1.2 #ApplicationLabel
Name of the application. This name will be displayed below the application icon on the device.
4.2.1.3 #DeviceCapabilities
You can add device capabilities like:
#DeviceCapabilities: location-services
Which adds the location capabilities. Example in the Location & GPS Tutorial in the forum.
4.2.1.6 #IgnoreWarnings
The compiler adds warnings in the Log Tab, you can ignore warnings.
Details in Test Compile / Warnings.
4.2.1.8 #PlistExtra
List of extra keys.
PlistExtra: <key>UIFileSharingEnabled</key><true/>
4.2.1.9 #URLScheme
Allows Dropbox synchronization using the iDropboxSync library.
For more information look at the DropboxSyncTutorial in the forum.
4.2.1.10 #Version
Program version attribute.
4 The IDE / 4.2 Code area 67 B4i Beginner's Guide
In the IDE it is possible to undo the previous operations and redo undone operations.
Click on to undo and on to redo.
In the IDE a subroutine can be collapsed to minimize the number of lines displayed.
Hovering with the mouse over the collapsed routine name shows its content.
4 The IDE / 4.2 Code area 68 B4i Beginner's Guide
Example:
Then you can add the subroutines between the two limits:
Then clicking on
shows the beginning of the code, not all the routines in the region.
4 The IDE / 4.2 Code area 69 B4i Beginner's Guide
- Toggle All
Expands the collapsed
routines and collapses the
extended routines and
regions.
- Expands All
Expands the whole code
- Collapse All
Collapses the whole code.
Clicking on .
To select the bloc press Alt and move the mouse cursor.
4 The IDE / 4.2 Code area 72 B4i Beginner's Guide
Example:
Click on txfResult to select it.
Look in:
A selected part of the code can be set to comment lines or set to normal.
Original code
Click on .
4.2.9 Bookmarks
You can set 'bookmarks' anywhere in the code and jump forward and backwards between these
bookmarks.
You will see this mark on the left of the line and a small black line in the right slider:
4.2.10 Indentation
Personally,
I prefer a value of 2.
4 The IDE / 4.2 Code area 76 B4i Beginner's Guide
Original code
Click on .
When you hover over code elements the on line help is displayed.
Examples:
Pressing a character
updates the list and shows
the parameter beginning
with that character.
Press Tab.
Modify 'EventName' to the EventName of the button, 'btnOK' in our case and press Return.
cvsLayer(2).DrawLine(x - d, y, x + d, y, Color, 1)
cvsLayer(2).DrawLine(x, y - d, x, y + d, Color, 1)
End Sub
If you want to add a code example you can use <code> </code> tags:
cvsLayer(2).DrawLine(x - d, y, x + d, y, Color, 1)
cvsLayer(2).DrawLine(x, y - d, x, y + d, Color, 1)
End Sub
When hovering over (copy) you can copy the code example to the clipboard.
Remove Draw
And copy.
4 The IDE / 4.2 Code area 82 B4i Beginner's Guide
Sometimes it is useful to jump from a subroutine call to the subroutine definition or to go from a
view or a variable to its definition.
The easiest way is to press Ctrl and click on the desired text.
Another way:
Double click on the text of the subroutine call, the
variable or the view to select it.
Click on .
When you select a single word, it is highlighted in dark blue and all the other occurrences in the
code are highlighted in light blue and in the scroll view on the right side.
With the slider you can move up or down the code to go to the other occurrences.
4.2.16 Debug
4.2.17 Breakpoints
In the click on .
Or, in the code, right click to show the pop up menu below and click on menu .
Click on to copy
the value to the Clipboard.
Sometimes, you will see yellow or green vertical lines in the left side od the IDE.
As soon as you modify a line it will be marked with a yellow vertical line on the right of the line
number meaning that this line was modified.
If we click on to save the project the yellow lines become green showing a modified code but
already saved. You can also press Ctrl + S to save the project.
If we leave the IDE and load the project again the green lines disappear.
4 The IDE / 4.2 Code area 87 B4i Beginner's Guide
In a comment:
If the cursor is on the line and you press Ctrl the url is highlighted in blue and if you click on it the
url it is executed. Hovering over the line with Ctrl pressed does also highlight the url.
In a String:
The cursor must be over the String variable and not over text.
4 The IDE / 4.3 Tabs 88 B4i Beginner's Guide
4.3 Tabs
There are 6 tabs at the bottom right corner of the IDE that display different windows.
When you start the default IDE all Tab windows are docked in the Tab area.
4.3.2 Float
Click on .
The Modules Tab Window is now floating, you can place it where you want on the screen even on a
second monitor.
You can also click on a Tab and while maintaining the mouse down, move the Tab.
Docking areas:
Top
Left
Right
Bottom
4 The IDE / 4.3 Tabs 92 B4i Beginner's Guide
If you mouve the mouse onto one of the docking area symbol, the Tab window will be either on top,
on the left, the right or on the bottom.
To bring it back to the Tabs, click on the window title and move it back to the Tabs.
4 The IDE / 4.3 Tabs 93 B4i Beginner's Guide
The Tabs move from the bottom of the screen vertically to the right side of the
screen and the Tab window is hidden.
As soon as you click somewhere else in the IDE the Tab is hidden again.
4 The IDE / 4.3 Tabs 94 B4i Beginner's Guide
4.3.4 Close
All the modules of the project and all subroutines of the selected module are listed in the Modules
window. The picture below has been reduced in height.
The Find Sub / Module function is a search engine, on the Top of the Modules Tab, to find
subroutines or Modules with a given name or with a given part of the name.
You can press Ctrl + E in the code to select the Modules Tab with the Find Sub / Module function.
Shows all modules and all Shows all modules and Shows all modules and
routines of the selected routines containing ‘b’. routines containing ‘btn’.
Module.
Clicking on one item shows the code of the selected module or routine, even if it's in another
module than the current one.
4 The IDE / 4.3 Tabs 98 B4i Beginner's Guide
This window lists all the files that have been added to the project.
These files are saved in the ‘Files’ subfolder under your main project folder.
The files can be of any kind: layouts, images, texts, etc.
When you answer Yes make sure to have a copy of the files you remove, because they are
removed from the Files folder, but not transferred to the Recycle Bin, which means that they
are definitely lost if you don't make a copy.
On top of the Files Manager window you can filter the files list.
4.3.7 Logs
We add the two lines 51 and 53 in the program 'SecondProgram' in the 'New' routine.
The number of the lines may be different from yours.
Application_Start
Number1 = 7 First log message
Number2 = 8 Second log message
Application_Active
B4A includes a warning engine. The purpose of the warning engine is to find potential
programming mistakes as soon as possible. The examples are from the Warnings project.
The compile-time warnings appear above the logs and in the code itself when hovering with the
cursor above the code line.
The code lines which cause a warning are underlined like this .
Clicking on the warning in the list will take you to the relevant code.
You, as the developer, can choose to ignore any warning. Adding an "ignore" comment will disable
all the warnings for that specific line:
You can also disable warnings from a specific type in the module by adding the #IgnoreWarning
attribute in the Project Attributes regions.
You find the warning numbers at the end of each warning line.
4 The IDE / 4.3 Tabs 103 B4i Beginner's Guide
End Select
End Sub
Wrong code
Sub Calc(Val1 As Double, Val2 As Double, Operation As String)
Correct code
Sub Calc(Val1 As Double, Val2 As Double, Operation As String) As Double
Wrong code
Private Sub CalcSum(Val1 As Double, Val2 As Double) As Double
Dim Sum As Double
Correct code
Private Sub CalcSum(Val1 As Double, Val2 As Double) As Double
Dim Sum As Double
Wrong code
Private Sub Calc(Val1, Val2 As Double, Operation As String) As Double
Correct code
Private Sub Calc(Val1 As Double, Val2 As Double, Operation As String) As Double
Wrong code
Private Sub SetHeight
h = 10
End Sub
Correct code
Private Sub SetHeight
Dim h As Int
h = 10
End Sub
The variable h was not declared. You see it also with the red color.
End Sub
This warning shows that the variable h is declared but not assigned any value.
Correct code see above.
4 The IDE / 4.3 Tabs 106 B4i Beginner's Guide
Wrong code
Dim lst As List
lst.Add("Test1")
Correct code
Dim lst As List
lst.Initialize
lst.Add("Test1")
Variables (objects) like List or Map must be initialized before they can be used.
Views added by code must also be initialized before they can be added to a parent view.
14: File '{1}' in Files folder was not added to the Files tab.
You are using a file which is in the Files folder, but was not added to the Files tab.
You should:
- Make a backup copy.
- Delete it from the Files subfolder.
- Add it to the project in the Files tab.
- Use Clean Files Folder (unused files) in the Tools menu.
You have files in the Files folder that are not used.
You should remove them from the Files folder.
Or you can clean the Files folder from within the Tools menu (see above).
4 The IDE / 4.3 Tabs 107 B4i Beginner's Guide
16: Layout file '{1}' is not used. Are you missing a call to Page.RootPanel.LoadLayout?
You have a layout file in the Files folder that is not used.
You should add LoadLayout or you can remove the layout file from the Files folder.
The given file is in the Files tab but is missing in the Files folder. You should add it.
See chapter Files.
Wrong code
Try
imvImage.Bitmap = LoadBitmap(File.DirAssets, "image.jpg")
Catch
End Try
Correct code
Try
imvImage.Bitmap = LoadBitmap(File.DirAssets, "image.jpg")
Catch
Log(LastException.Message)
End Try
20: View '{1}' was added with the designer. You should not initialize it.
A View defined with the Designer in a layout file must not be initialized!
Only views added by code need to be initialized.
You must add a view to a parent view before you can access its dimensions.
When you add a view by code its dimensions are defined when you add it with AddView.
23: Modal dialogs are not allowed in Sub Activity_Pause. It will be ignored.
24: Accessing fields from other modules in Sub Process_Globals can be dangerous as the
initialization order is not deterministic.
29: This sub should only be used for variables declaration or assignments of primitive values.
30: Variable name is the same as a module name. This can cause problems during debugging.
The ‘Libraries Manager’ tab contains a list of the available libraries that can be used in the project.
On the top of the tab you find a field to filter the libraries.
Enter ‘iH’ in the field and you get all libraries beginning with iH.
Note that in B4i all libraries have the prefix ‘i’ ?
The list of all additional libraries can be found here: Additional Libraries.
Quick Search allows to search for any text occurrences in the code of the whole project.
Examples with the SecondProgram code.
Example:
In each line you find the Module name and the line content.
Like in
Clicking on a line in the list moves the cursor directly to the selected occurrence in the code.
A as an example, enter lbl in the Search field and you get the window below where you find all
lines containing the text you entered, lbl in this example.
The search text is highlighted in all code Clicking on one of the lines in the list
lines containing this text. jumps directly to this line in the IDE.
This is a search engine to find all references for a given object (view, variable).
Click on the Tab or press F7 to get the screen below showing a list of all
code lines with the selected reference or the first object in the current line.
Click on or press F7 and you get the list below with all code lines containing
the selected object.
Moves backwards and forwards based on the navigation stack. This is useful to jump back and forth
between the last recent subs.
Opens the navigation stack menu. You can then choose the location with the up and down keys.
If you are working on two locations in the same module then you can split the code editor (it can be
split again vertically):
Horizontally Vertically
You can also double click on the small rectangles to split the screen.
4 The IDE / 4.3 Tabs 114 B4i Beginner's Guide
If you are working with multiple modules you can move the modules out of the main IDE as
separate windows.
Ctrl + E - searches for sub or module. Very useful when working with large projects.
Not exactly related to navigation but is also useful when working with large projects.
Details in Find all references.
5.1 Coordinates
In iOS there is a distinction between the coordinates you specify in your drawing code and the pixels of the
underlying device. When using native drawing technologies such as Quartz, UIKit, and Core Animation, the
drawing coordinate space and the view’s coordinate space are both logical coordinate spaces, with
distances measured in points. These logical coordinate systems are decoupled from the device coordinate
space used by the system frameworks to manage the pixels onscreen.
The system automatically maps points in the view’s coordinate space to pixels in the device coordinate
space, but this mapping is not always one-to-one. This behavior leads to an important fact that you should
always remember:
The purpose of using points (and the logical coordinate system) is to provide a consistent size of output that
is device independent. For most purposes, the actual size of a point is irrelevant. The goal of points is to
provide a relatively consistent scale that you can use in your code to specify the size and position of views
and rendered content. How points are actually mapped to pixels is a detail that is handled by the system
frameworks. For example, on a device with a high-resolution screen, a line that is one point wide may
actually result in a line that is two physical pixels wide. The result is that if you draw the same content on two
similar devices, with only one of them having a high-resolution screen, the content appears to be about the
same size on both devices.
B4i B4A
1 Point = 1 dip (device independent pixel)
B4i B4A
Coordinates Point Pixel
View dimensions Point Pixel
Drawing coordinates Point Pixel
Adding a view AddView(10, 10, 150, 50) AddView(10dip, 10dip, 150dip,
50dip)
Standard dpi 160 16’
(dots per inch)
GetDeviceLayoutValues Example 320 dpi screen
Scale Always 1 2
NonnormalizedScale 2 ---
Width Point Pixel
Height Point Pixel
1 Pixel 1 Point / NonnormalizedScale ---
1 Point --- 1 Pixel * Scale
5 Screen sizes and resolutions 116 B4i Beginner's Guide
5.2.1 Screens
The current screen sizes are, only devices supported by iOS 7+ are shown:
StatusBar height 20
NavigationBar / ToolBar height 44
NavBar / ToolBar icon 22 x 22
TabBar height 49
TabBar icon 25 x 25
5 Screen sizes and resolutions 117 B4i Beginner's Guide
You should provide different icon files for the different screen scales.
In an Initialize method you must use the generic file name. iOS selects automatically the correct file
according to the device scale.
For the navigation between different pages you should use the standard iOS objects instead of
reinventing the wheel. Users are used to them and feel directly ‘at home’!
These are explained in the User Interfaces chapter.
It’s up to you to define what layout you want, what you want to display at the same time and how
you want to navigate through the different displays.
In some cases it might be better to have one or two layouts (portrait and / or landscape) for iPhones
and one or two layouts for iPads. Use as little layout variants as needed and use the different tool to
adapt them to fit the different screen sizes.
As iPads have bigger screens than phones it could be interesting to display more information on
iPads than on iPhones.
Depending on the application, it could be interesting to display one panel on pages in portrait on
iPhones and display two panels side by side on a same page on iPads.
There are no general rules nor templates for user interfaces. They depend on the kind of application,
the kind of information to display on what screen size, the number of different pages depending on
the screen size and the information, etc.
Several tools are at your disposal to design the layouts, these are explained in the following
chapters.
The Visual Designer.
The Abstract Designer.
Anchors.
Designer Scripts.
AutoScale.
6 The Designer 120 B4i Beginner's Guide
The Designer allows generating layouts with the Abstract Designer and / or with a real device.
The default Visual Designer looks like this, the layout in the Abstract Designer is from the
SecondProgram project.
6 The Designer / 6.1 The menu 121 B4i Beginner's Guide
This menu allows you to select the view you want to add to the current layout.
When you select a view in the list, all the properties of the selected
view are displayed in the Properties window.
You can select several Views at the same time and change common
properties.
The files you add are copied to the Files folder of the project and can
be accessed in the code in the File.DirAssets folder.
6 The Designer / 6.2 Designer Windows 124 B4i Beginner's Guide
In the Scrip windows you can add code to position and resize Views.
Two windows are available:
Script - General Code valid for all layout variants.
Script - Variant Specific code for the selected variant.
The displayed layout in the picture below is from the SecondProgram project.
You can define your own Visual Designer layout, rearrange the windows in size and position,
docked or floating.
On the top right of each window two icons allow you to manage the behavior of this window.
Options.
Dock as Document.
Auto Hide.
6.3.1 Float
Click on
The Files windows is independent from the Visual Designer and is removed from the Views
window. You can move it where ever you want on the screen.
6 The Designer / 6.3 Floating Windows 128 B4i Beginner's Guide
6.3.2 Dock
Click on
The window is removed from its parent window and added to the Abstract Designer window.
Click either on or on .
The three windows: Files, Variants and Views Tree are moved as Tabs to the left border of the
Visual Designer. The Properties window width is increased.
When you click somewhere else, outsides the selected window, hides it automatically.
Click on in the title to move the windows back to their previous position.
6 The Designer / 6.3 Floating Windows 130 B4i Beginner's Guide
6.3.5 Maximize
To set it back to its previous size, click on in the top right corner.
6 The Designer / 6.3 Floating Windows 131 B4i Beginner's Guide
When a window is set as Dock as Document two other options are available.
I moved the two Script widows as Dock as Document onto the Abstract Designer window.
That way the Views and Properties windows is much higher.
6 The Designer / 6.4 Tools 133 B4i Beginner's Guide
6.4 Tools
Checking a view generates its reference in the Process_Globals Sub in the code.
This is needed to make the view being recognized and allow the autocomplete function.
End Sub
Click on to generate the references and sub frames and close the window.
Click on to select all views in the list,
Click on to clear the current selections.
6 The Designer / 6.4 Tools 134 B4i Beginner's Guide
The grid is an invisible grid with a given size. The default grid size is 10 pixels. That means that all
positions 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.
The value is saved in the layout file, you will get the same value when you reload this layout.
These files are saved to the Files folder of the project and can
be accessed in the code in the Files.DirAssets folder.
Oui = Yes
Non = No
Annuler = Cancel
When you answer Yes make sure to have a copy of the files you remove, because they are
removed from the Files folder, but not transferred to the Recycle Bin, which means that they
are definitely lost if you don't make a copy.
6 The Designer / 6.6 Properties list 136 B4i Beginner's Guide
Explanation of some general properties for all types of Views in the next chapters.
6 The Designer / 6.6 Properties list 137 B4i Beginner's Guide
Name Name of the view. It is good practice to give meaningful names. Common
usage is to give a 3 character prefix and add the purpose of the view. In the example, the view is of
type Label and its purpose is to show a result. So we give it the name "lblResult", "lbl" for
Label and "Result" for the purpose. This does not take much time during the design of the layout
but saves a lot of time during coding, debugging 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 view's events. By default,
the Event Name is the same as the view's name like in the example. The Events of several Views
can 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 the
keyboard in the btnEvent_Click routine.
Tag This is a place holder which can be used to store additional data. Tag can
simply be text but can also be any other kind of object.
Tag is used in the SecondProgram example for the numeric buttons click events management in the
btnEvent_Click routine.
Parent Name of the parent view. Main, in the example. The parent view can be
changed in selecting the new one in the list.
6 The Designer / 6.6 Properties list 138 B4i Beginner's Guide
Left X coordinate of the left edge of the View from the left edge of its parent
View, in points.
Top Y coordinate of the upper edge of the View from the upper edge of its parent
View, in points.
You should only use these layout variants and not specific layouts, even though it is possible, and
fine-tune them with Anchors and with Designer Scripts.
6 The Designer / 6.7 Layout variants 140 B4i Beginner's Guide
In the Abstract Designer we can check the look of the layout on different screens.
In the Layout menu you can select the screen size to check.
We see that:
On the 3.5’’ screen the bottom views are outsides the screen.
On the 4.7’’ and the 5.5’’ screen the views don’t fill the screen.
6 The Designer / 6.7 Layout variants 142 B4i Beginner's Guide
We see that:
lblTitle and pnlToolBox fill the whole width, pnlTest fills the screen, only the 4 buttons are
not moved.
For this we can add the code below in DesignerScript to center the 4 buttons.
'All variants script
'AutoScaleAll
btnTest2.Right = 50%x - 10
btnTest1.Right = btnTest2.Left - 20
btnTest3.Left = 50%x + 10
btnTest4.Left = btnTest3.Right + 20
The text sizes in the Label and in the Buttons have not changed, but not really necessary, the text
sizes in the iOS Navigation and Toolbar buttons aren’t changed either.
Nevertheless, it could be done with AutoScale.
6 The Designer / 6.7 Layout variants 143 B4i Beginner's Guide
Select .
We don’t center the buttons like in the portrait layout but move them equally spaced over the
height.
6 The Designer / 6.7 Layout variants 146 B4i Beginner's Guide
iPad screen
6.8.2 Zoom
With you can hide the zoom cursor and show it again with .
With the cursor you can set the zoom level you want.
With the bottom and side cursors you can move the layout vertically or horizontally.
6 The Designer / 6.8 Abstract Designer 149 B4i Beginner's Guide
Most editing functions can be accessed in a popup menu which is displayed when you right click on
a view.
Add View
Cut
Copy
Paste
Duplicate
Undo
Redo
Horizontal Anchor
Vertical Anchor
Bring To Front
Send To Back
Generate
Right clicking somewhere on the Activity area shows the context menu with some functions
disabled which are not relevant for a Page.
Right click somewhere on the parent view where you want to add a new view and move the cursor
onto .
This function is the same as the Add View function in the Visual Designer menu.
6.8.3.2 Cut
These two functions allow you to undo or redo the last operations.
6 The Designer / 6.8 Abstract Designer 152 B4i Beginner's Guide
or
6.8.3.8 Generate
A popup menu allows you to select what code you want to generate, the possibilities depend on the
type of the selected view.
Click
Generates the Click event routine frame.
Sub btnAction_Click
End Sub
LongClick
Generates the LongClick event routine frame.
Sub btnTest1_LongClick
End Sub
In the Properties window you can change all properties common to the selected views.
You can change all these properties because they are the
same for the four views selected in the example.
If you select views of different types, only the properties common to the selected views can be
changed.
6.8.5 Example
Let us take a simple example with a layout in portrait mode, like the image below.
Click on .
Now you can switch between the two layouts by selecting the
layout in the Variants window.
6 The Designer / 6.9 Adding views by code 160 B4i Beginner's Guide
It is also possible to add views by code instead of using the Designer with a device or the Abstract
Designer.
Advantage: None.
Disadvantage: You have to define almost everything and AutoScale doesn’t work.
Note that you should avoid adding views in code but use the Designer with Designer Scripts.
For the positions and dimensions of the views on the screen two options are available:
Points, scale independent.
The default density is 160 dpi dots per inch (pixels per inch).
All coordinates refer to this density, iOS adapts the values internally to the scale.
No dip values like in Android. More details in Coordinates.
%x and %y represent distances proportional to the current screen width and height.
20%x = 0.2 * Page1.RootPanel.Width
90%y = 0.9 * Page1.RootPanel.Height
20%x = PerXToCurrent(20) PerXToCurrent is a Keyword %x is the Shortcut
90%y = PerYToCurrent(90)
6 The Designer / 6.9 Adding views by code 161 B4i Beginner's Guide
Example:
Let us put a Label on top of the screen and a Panel below it with a Label and a Button on it:
Sub Process_Globals
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
lblTitle.Initialize("")
lblTitle.Color = Colors.Red
lblTitle.Font = Font.CreateNew(20)
lblTitle.TextColor = Colors.Blue
lblTitle.TextAlignment =lblTitle.ALIGNMENT_CENTER
lblTitle.Text = "Title"
pnlTest.Initialize("")
pnlTest.Color = Colors.LightGray
lblPanelTitle.Initialize("")
lblPanelTitle.Color = Colors.Red
lblPanelTitle.Font = Font.CreateNew(16)
lblPanelTitle.TextColor = Colors.Blue
lblPanelTitle.TextAlignment = lblPanelTitle.ALIGNMENT_CENTER
lblPanelTitle.Text = "Panel test"
End Sub
Code explanations:
If the Label had been added in the Designer, all the above code wouldn't have been necessary
because the properties would already have been defined in the Designer.
Note that we add the views to their parent views in Page1_Resize and not in Application_Start
because the real size of Page1.RootPanel is not known before!
6.10 Anchors
The Designer has two ‘special’ features to size views, the Horizontal Anchor and the Vertical
Anchor.
Horizontal Anchor
LEFT
RIGHT
BOTH
Setting the Horizontal Anchor property to BOTH is similar to the SetLeftAndRight function in the
Designer Scripts.
6 The Designer / 6.10 Anchors 166 B4i Beginner's Guide
Vertical Anchor
TOP
TOP is the default value.
The top edge is anchored to the top edge of
the parent view with the distance given in the
Top property.
No anchor symbol is shown.
BOTTOM
The bottom edge is anchored to the bottom
edge of the parent view with the distance given in the
Bottom Edge Distance property.
The Top property is no more available because
it is defined by the Height and the bottom
anchor!
The dot on the bottom edge shows the anchor.
BOTH
Both edges are anchored to
the parent view with
distances defined in the Top
and Bottom Edge Distance
properties.
The Height property is no more available
because it is defined by the anchors!
The dots on the two edges show the anchors.
What happens when we set the horizontal anchor of the two views below to BOTH and change the
parent view width?
The left views right edge is anchored to the right edge of the parent view with the Right Edge
Distance.
The right views left edge is anchored to the left edge of the parent view with the Left distance.
If we increase the width of the parent view we get the layout below.
The left views right edge is still at the Right Edge Distance from the parent views right edge.
The right views left edge is still at the Left distance from the parent views left edge.
The result is an overlapping of both views.
In this case you must adjust the views in the Designer Scripts with the SetLeftAndRight method!
For example:
LeftView.SetLeftAndRight(0, 67%x)
RightView.SetLeftAndRight(33%x, 100%x)
6 The Designer / 6.10 Anchors 168 B4i Beginner's Guide
The examples shown in this chapter are based on the Anchors project in the Designer folder.
First we add a label on top of the screen which should cover the whole width and stay on top.
Click on .
Click on .
Left = 0
Top = 0
Width = 320 full layout width
Height = 40
Click on .
In the Views Tree window we see that Label2 is shifted to the right
because its parent view is Panel1 and not Main like for Label1 and
Panel1!
And the result looks like the pictures below in portrait and landscape screen orientations.
To demonstrate the anchor feature we move, in the Abstract Designer, the top edge of Panel1
upwards.
We see that the top edge of Label2 moves with the top edge
of Panel1 and the bottom edge remains at its place!
Now, we add another Panel onto the left half of We set the vertical anchor to BOTH.
the screen and vertically positioned between
Label1 and Panel1 leaving a small space.
Now, we add a ScrollView on the right We set the horizontal anchor to RIGHT.
half of the screen also positioned between We set the vertical anchor to BOTH.
Label1 and Panel1 leaving a small space.
6 The Designer / 6.10 Anchors 173 B4i Beginner's Guide
But the Width property remains the same and that’s why we get the gap between the two views
when the screen width is wider than the layout screen width.
6 The Designer / 6.10 Anchors 174 B4i Beginner's Guide
'AutoScaleAll
Panel2.Width = 50%x - 15
ScrollView1.SetLeftAndRight(50%x + 5, 100%x - 10)
The anchors are valid in the AbstractDesigner but not in Designer Scripts.
The "Designer Scripts" tool will help you fine tune your layout and easily adjust it to different
screens.
It is not recommended to create many layout variants but use AutoScale and the Designer.
The idea is to combine the usefulness of the visual designer with the flexibility and power of
programming code.
You can write a simple script to adjust the layout based on the dimensions of the current device and
immediately see the results. You can immediately see the results on the Abstract Designer. This
allows you to test your layout on different screen sizes.
6 The Designer / 6.11 Designer Scripts 176 B4i Beginner's Guide
6.11.1 General
Every layout file can include script code. The script is written inside the Visual Designer in the
Script windows:
Once you press, in the Script window menu, on the Run Script button (or F5), the script is
executed and the connected device / emulator and abstract designer will show the updated layout.
The same thing happens when you run your compiled program. The (now compiled) script is
executed after the layout is loaded.
The general script is first executed followed by the variant specific script.
The script language is very simple and is optimized for managing the layout.
6 The Designer / 6.11 Designer Scripts 177 B4i Beginner's Guide
Ctrl + C Copy
Ctrl + X Cut
Ctrl + V Paste
Ctrl + Z Undo
Ctrl + Shift + Z Redo
Ctrl + Q Block Comment
Ctrl + W Block Uncomment
Outdent
Indent
F3 Find / Replace
F5 Run
6 The Designer / 6.11 Designer Scripts 178 B4i Beginner's Guide
- Text - Gets or sets the view's text. TextSize and Text properties are only available to views that
show text.
- SetLeftAndRight (Left, Right) - Sets the view's left and right properties. This method changes the
width of the view based on the two values.
- SetTopAndBottom (Top, Bottom) - Sets the view's top and bottom properties. This method changes
the height of the view based on the two values.
- AutoScaleRate - Sets the scaling rate, a value between 0 and 1. The default value is 0.3
Example: AutoScaleRate(0.5)
- If . Else If . Else . condition blocks - Both single line and multiline statements are
supported. The syntax is the same as the regular If blocks.
6 The Designer / 6.11 Designer Scripts 179 B4i Beginner's Guide
6.11.6 Autocomplete
When you begin writing the Autocomplete function shows all possible keywords or view names
containing the written text with the help of the selected keyword.
Example: Au, shows all AutoScale methods.
%x and %y values are relative to the view that loads the layout.
Usually it will be the Page. However if you use Panel.LoadLayout then the values are
relative to the size of this panel.
Variables - You can use variables in the script. You do not need to declare the variables
before using them (there is no Dim keyword in the script).
6 The Designer / 6.11 Designer Scripts 180 B4i Beginner's Guide
6.11.8 Example
The first step is to add the views and position them with the visual designer (you do not need to be
accurate).
Now we will select the designer scripts tab and add the code.
Note that the views are locked when the designer scripts tab is selected.
btnTest2.Left = btnTest5.Left
btnTest2.Bottom = btnTest5.Top - Space
btnTest8.Left = btnTest5.Left
btnTest8.Top = btnTest5.Bottom + Space
The result:
5.5’’
6 The Designer / 6.11 Designer Scripts 183 B4i Beginner's Guide
iPad
6 The Designer / 6.12 AutoScale 184 B4i Beginner's Guide
6.12 AutoScale
Since B4i version 1.2 two new functions have been added:
AutoScaleRate(rate)
AutoScaleAll
Larger devices offer a lot more available space. The result is that even if the physical size of a view
is the same, it just "feels" smaller.
Some developers use %x and %y to specify the views size. However the result is far from being
perfect. The layout will just be stretched.
The solution is to combine the "dock and fill" strategy with a smart algorithm that increases the
views size and text size based on the running device physical size.
AutoScale calculates a Scale factor depending on the reference layout size and the current device
size and multiplies the Left, Top, Width and the Height properties by this Scale factor.
If the view has a Text property, Font Size is also multiplied by this Scale factor.
You can play with the 'rate' value. The rate determines the change amount in relation to the devices
physical size.
A value of 0 means no change at all. A value of 1 is almost similar to using %x and %y values. If
the physical size is twice the size of the standard phone then the size will be twice the original size.
Values between 0.2 and 0.5 seem to give good results. The default value is 0.3.
Be careful when you ‘downsize’ a layout defined for a big screen to a small screen. The views may
become very small.
The abstract designer is useful to quickly test the effect of this value.
Functions:
AutoScaleRate(rate) Sets the rate value.
Example : AutoScaleRate(0.5) Sets the rate value to 0.5.
The process end is less determinant. It will happen sometime after the user has closed the program.
Another delicate point happens when there is a major configuration change in the device. The most
common is an orientation change (the user rotates the device). When such a change occurs the
current pages are destroyed and then recreated. Now it is possible to create the page according to
the new configuration (for example, we now know the new screen dimensions), in the Page_Resize
event routine.
7 Process life cycle 187 B4i Beginner's Guide
One more important event is Page_Resize, this event is raised just after Application_Start or after
an orientation change.
In this event the current size is known allowing to adjust view dimensions if needed and initialize
Canvases.
The process will continue running until the user closes the application. This happens when the user
presses on the home button.
Application_Background will be called when the application is moving to the background. This is
the place to save the user data and also to save the state. You should assume that the process will be
killed shortly after this sub.
Normal applications do not run in the background. There are no services in iOS.
Application_Active will be raised when the app is active. Which means that the user can interact
with it. It will follow Application_Start and Application_Foreground events.
Application_Inactive will be raised when the app is still in the foreground but the user cannot
interact with it. It will be raised before Application_Background. It can also be raised when there is
an interruption such as a phone call. In this case Application_Inactive will be raised and if the user
doesn't answer the call Application_Active will be raised.
Application_Foreground will be called after the app transitions from the background to the
foreground. This event will only fire if the process was not killed while the app was in the
background.
The last event is Application_OpenUrl. This event is fired when another app sends an URL to the
system that your app is registered to. This is another way to start applications. This is how for
example B4i-Bridge launches the apps during debugging.
7 Process life cycle 188 B4i Beginner's Guide
When you start the IDE you will see the default template below.
'Code module
#Region Project Attributes
#ApplicationLabel: B4i Example
#Version: 1.0.0
'Orientation possible values: Portrait, LandscapeLeft, LandscapeRight and
PortraitUpsideDown
#iPhoneOrientations: Portrait, LandscapeLeft, LandscapeRight
#iPadOrientations: Portrait, LandscapeLeft, LandscapeRight, PortraitUpsideDown
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
End Sub
End Sub
End Sub
All ‘global’ variables must be declared here, ‘global’ means outsides sub routines.
If you need variables accessible from everywhere in the project you must declare them as Public,
otherwise as Private. Public variables live as long as the process lives.
This sub is called once when the process starts (this is true for all modules, not just Main module).
Not all types of objects can be declared as Public.
All of the views for example cannot be declared as process global variables.
This routine is called each time the page size is changed, mostly after an orientation change.
Generally there are two types of mechanisms that allow you to save the page state.
Information that is only relevant to the current application instance can be stored in one or more
process 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 storage
at this point. Otherwise the changes may be lost.
7.5 Application_Background
This routine will be called when the application is moving to the background. This is the place to
save the user data and also to save the state. You should assume that the process will be killed
shortly after this sub.
8 Variables and objects 190 B4i Beginner's Guide
Primitive types are always passed by value to other subs or when assigned to other variables.
For example:
Private Sub S1
Dim A As Int
A = 12 The variable A = 12
S2(A) It's passed by value to routine S2
Log(A) ' Prints 12 Variable A still equals 12, even though B was changed in routine S2.
End Sub
All other types, including arrays of primitive types and strings are categorized as non-primitive
types.
When you pass a non-primitive to a sub or when you assign it to a different variable, a copy of the
reference is passed.
This means that the data itself isn't duplicated.
It is slightly different than passing by reference as you cannot change the reference of the original
variable.
For Views it is useful to add to the name a three character prefix that defines its type.
Examples:
lblCapital lbl > Label Capital > purpose
txfInterest txf > TextField Interest > purpose
btnNext btn > Button Next > purpose
Variables are declared with the Private, Public or Dim keyword followed by the variable name
and the As keyword and followed by the variable type.
Private Declares variables accessible only in the environment where they are declared.
Variables declared in a Module are accessible only in this Module.
Variables declared in a Sub are accessible only in this Sub.
Examples:
Public Capital As Double Declares three variables as Double,
Public Interest As Double double precision numbers.
Public Rate As Double
The names of the variables separated by commas and followed by the type declaration.
Private i = 0, j = 2, k = 5 As Int
Private txt = "test" As String, value = 1.05 As Double, flag = False As Boolean
To allocate a value to a variable write its name followed by the equal sign and followed by the
value, like:
Capital = 1200
LastName = "SMITH"
Note that for Capital we wrote just 1200 because Capital is a number.
But for LastName we wrote "SMITH" because LastName is a string.
Strings must always be written between double quotes.
Arrays are collections of data or objects that can be selected by indices. Arrays can have multiple
dimensions.
The declaration contains the Public or Private keyword followed by the variable name LastName,
the number of items between brackets (50), the keyword As and the variable type String.
Examples:
Public LastName(50) As String One dimension array of strings, total number of items 50.
Public Matrix(3, 3) As Double Two dimensions array of Doubles, total number of items 9.
Public Data(3, 5, 10) As Int Three dimensions array of integers, total number of items 150.
8 Variables and objects 194 B4i Beginner's Guide
The last index is equal to the number of items in each dimension minus 1.
LastName(49), Matrix(2,2), Data(2,4,9)
This example shows how to access all items in a three dimensional array.
For i = 0 To 2
For j = 0 To 2
For k = 0 To 2
Data(i, j, k) = ...
Next
Next
Next
We declare the variable NbPers As Int and set its value to 50, NbPers = 50 .
Then we declare the arrays with this variable instead of the number 50.
The big advantage is if at some point we need to change the number of items, we change only ONE
value.
For the Data array we could use the following code.
For i = 0 To NbX - 1
For j = 0 To NbY -
For k = 0 To NbZ - 1
Data(i, j, k) = ...
Next
Next
Next
Views or objects can also be in an Array. The following code shows an example:
The individual names (b1, b2 etc.) must also be declared.
In the example below the Buttons are added to the Application by code.
Sub Process_Globals
Private Buttons(7) As Button
End Sub
For i = 0 To 6
Buttons(i).Initialize("Buttons")
Activity.AddView(Buttons(i), 10, 10 + i * 60, 150, 50)
Buttons(i).Tag = i + 1
Buttons(i).Text = "Test " & (i + 1)
Next
End Sub
Sub Buttons_Click
Private btn As Button
btn = Sender
The Buttons could also have been added in a layout file, in that case they must neither be initialized,
nor added to the Activity and the Text and Tag properties should also be set in the Designer.
In that case the code would look like this:
Sub Process_Globals
Private btn1, btn2, btn3, btn4, btn5, btn6, btn7 As Button
Private Buttons() As Button
End Sub
Buttons = Array As Button (btn1, btn2, btn3, btn4, btn5, btn6, btn7)
End Sub
Sub Buttons_Click
Dim btn As Button
btn = Sender
A Type cannot be private. Once declared it is available everywhere (similar to Class modules).
The best place to declare them is in the Process_Globals routine in the Main module.
The new personal type is Person, then we declare either single variables or arrays of this personal
type.
User(1).LastName
User(1).FirstName
It is possible to assign a typed variable to another variable of the same type, as shown below.
CurrentUser = User(1)
8 Variables and objects 197 B4i Beginner's Guide
8.4 Casting
B4i casts types automatically as needed. It also converts numbers to strings and vice versa
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 references 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.
Sub Process_Globals
Dim Btn1, Btn2, Btn3 As Button
End Sub
Sub Process_Globals
End Sub
Sub Btn_Click
Dim btn As Button
btn = Sender ' Cast the Object to Button
btn.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub
8 Variables and objects 198 B4i Beginner's Guide
8.5 Scope
To access Public variables in other modules than the module where they were declared their names
must have the module name they were declared as a prefix.
Example:
Variable defined in a module with the name : MyModule
Sub Process_Globals
Public MyVar As String
End Sub
Variables declared in a subroutine are local to this subroutine even if they are declared as Public
which is none sense.
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 other
value you have defined in the code and are 'destroyed' when the subroutine is left.
8 Variables and objects 199 B4i Beginner's Guide
8.6 Tips
A view can be assigned to a Private variable so you can easily change the common properties of
the view.
9 Modules
At least one module exists, the main module.
Its name is always Main and cannot be changed.
To add a new module click on either Class Module or Code Module in the
IDE menu Project / Add New Module.
To add an existing module click on Add Existing Module in the IDE menu Project.
The purpose and advantage of code modules is sharing same code in different programs, mainly for
calculations or other general management.
Some code modules, called utilities, are already published by Erel in the forum:
DBUtils, Database management utilities.
DateUtils, Date calculations.
ChartsFrameWork, Charts drawing module.
9 Modules 202 B4i Beginner's Guide
Modules are in principle saved it the folder of each project using it.
Modules useful in several project can be shared without loading them in each projects folder, that’s
the purpose of shared modules.
Shared module files must be stored in a specific ‘Shared Modules’ folder which must be defined in
the IDE menu Tools - Configure Paths.
You can see that a module was loaded from the shared folder in the list of modules:
Class module.
Shared module.
Adding a shared module to a project is done in the same way as adding a non-shared module.
You choose Project -> Add Existing Module. If the module file is in the ‘SharedModules’ folder
then the module will be loaded as a shared module and will not be copied to the project folder.
If you want to convert a non-shared module to a shared module then you need to manually move the
module file to the shared modules folder and reload the project
10 Basic Language 204 B4i Beginner's Guide
10 Basic language
In computer programming, BASIC (an acronym which stands for Beginner's All-purpose Symbolic
Instruction 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 Thomas
Eugene 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, which
was something only scientists and mathematicians tended to do. The language and its variants
became widespread on microcomputers in the late 1970s and 1980s.
BASIC remains popular to this day in a handful of highly modified dialects and new languages
influenced by BASIC such as Microsoft Visual Basic (source Wikipedia).
This is a summary of the more detailed explanations in Process and Activity life cycle.
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
End Sub
End Sub
End Sub
The program goes through following routines when starting from top to down:
10.1.5.1 Application_Foreground
This event is raised is called when the Application is in the Foreground, visible on the screen.
10.1.5.2 Application_Active
This event is raised is called when the Application is Active.
10.1.5.3 Application_Inactive
This event is raised is called when the Application gets Inactive.
10 Basic Language 206 B4i Beginner's Guide
10.2 Expressions
Precedence
Operator Example Operation
level
+ 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 of
Logarithm Logarithm(x, y) 1 Logarithm of
Precedence level: In an expression, operations with level 1 are evaluated before operations with
level 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
- 22 = - 4
(-2)2 = 4
10 Basic Language 207 B4i Beginner's Guide
In computer science in relational expressions an operator tests some kind of relation between two
entities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 >= 3).
In B4i these operators return True or False, depending on whether the conditional relationship
between the two operands holds or not (source Wikipedia).
In computer science, a Boolean expression is an expression that produces a Boolean value when
evaluated, i.e. one of True or False. A Boolean expression may be composed of a combination of
the Boolean constants True or False, Boolean-typed variables, Boolean-valued operators, and
Boolean-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 True
10 Basic Language 208 B4i Beginner's Guide
The If - Then - Else structure allows to operate conditional tests and execute different code sections
according to the test result.
General case:
If test1 Then
' code1
Else If test2 Then
' code2
Else
' code3
End If
The tests can be any kind of conditional test with two possibilities True or False.
Some examples:
If b = 0 Then
a = 0 The simplest If - Then structure.
End If
If b = 0 Then
a = 0 The simplest If - Then - Else structure.
Else
a = 1
End If
If b = 0 Then a = 0 : c = 1
The colon character ' : ' in the line above is treated in B4i like a CarriageReturn CR character.
10 Basic Language 210 B4i Beginner's Guide
The Select - Case structure allows to compare a TestExpression with other Expressions and
to execute different code sections according to the matches between the TestExpression and
Expressions.
General case:
Examples:
Select Value
Case 1, 2, 3, 4 The Value variable is a numeric value.
Case Panel1.ACTION_MOVE
Case Panel1.ACTION_UP
End Select
End Sub
10 Basic Language 211 B4i Beginner's Guide
In a For – Next loop a same code will be executed a certain number of times.
Example:
If the step value is equal to '+1' the step keyword is not needed.
For i = n3 To 0 Step -1
Next
In VB:
The increment variable is added after the Next Keyword.
The loop type is specified after the Exit keyword.
Example:
Next
Sum = 0
For Each n As Int In Numbers
Sum = Sum + n
Next
Sum = 0
For i = 0 To Numbers.Length - 1
Sum = Sum + Numbers(i)
Next
10 Basic Language 214 B4i Beginner's Guide
10.4.3 Do - Loop
Do While test
' code
If a = 0 Then Exit If a = 0 then exit the loop
' code
Loop
10 Basic Language 215 B4i Beginner's Guide
Examples:
Do Until Loop :
Private i, n As Int
i = 0
Do Until i = 10
' code
i = i + 1
Loop
Do While Loop:
Private i, n As Int
i = 0
Do While i < 10
' code
i = i + 1
Loop
tr.Initialize(File.OpenInput(File.DirDocuments, "test.txt"))
lstText.Initialize
line = tr.ReadLine
Do While line <> Null
lstText.Add(line)
line = tr.ReadLine
Loop
tr.Close
VB accepts also the following loops, which are not supported in B4i.
Do Do
' code ' code
Loop While test Loop Until test
10 Basic Language 216 B4i Beginner's Guide
10.5 Subs
A Subroutine (“Sub”) is a piece of code. It can be any length, has a distinctive name and a defined
scope (in the means of variables scope discussed earlier). In Basci4i code, a subroutine is called
“Sub”, and is equivalent to procedures, functions, methods and subs in other programming
languages. The lines of code inside a Sub are executed from first to last.
It is not recommended to have too long Subs, they get less readable.
10.5.1 Declaring
It starts with the keyword Private or Public, depending on the scope, followed by the keyword Sub,
followed by the Subs name, followed by a parameter list, followed by the return type and ends with
the keywords End Sub.
Subs are always declared at the top level of the module, you cannot nest two Subs one inside the
other.
When you want to execute the lines of code in a Sub, you simply write the Sub’s name.
For example:
Interest = CalcInterest(1234, 5.2)
A subroutine declared in a code module can be accessed from any other module but the name of the
routine must have the name of the module where it was declared as a prefix.
Example: If the CalcInterest routine is declared in module MyModule then calling the routine must
be :
Interest = MyModule.CalcInterest(1234, 5.2)
instead of:
Interest = CalcInterest(1234, 5.2)
10 Basic Language 217 B4i Beginner's Guide
10.5.4 Naming
Basically, you can name a Sub any name that is legal for a variable. It is recommended to name the
Sub with a significant name, like CalcInterest in the example, so you can tell what it does from
reading the code.
There is no limit on the number of Subs you can add to your program, but it is not allowed to have
two Subs with the same name in the same module.
10.5.5 Parameters
Parameters can be transmitted to the Sub. The list follows the sub name. The parameter list is put in
brackets.
The parameter types should be declared directly in the list.
10.6 Events
In Object-oriented programming we have objects which can react on different user actions called
events.
The number and the type of events an object can raise depend on the type of the object.
User interface objects are called 'Views' in iOS.
Events
ValueChanged
ScrollChanged
IndexChanged
TextChanged
PageFinished
EnterPressed
ItemSelected
OverrideUrl
LongClick
BeginEdit
EndEdit
Resize
Touch
Click
Views
Button
TextField
TextView
ImageView
Label
Panel
ScrollView
Slider
Picker
Stepper
Switch
SegmentedControl
Slider
Stepper
WebView
10 Basic Language 219 B4i Beginner's Guide
LongClick Event raised when the user clicks on the view and holds it pressed for a while.
Example:
Private Sub Button1_LongClick
' Your code
End Sub
The X and Y coordinates of the finger positions are given in Points not in Pixels.
Example:
Private Sub Panel_Touch (Action As Int, X As Float, Y As Float)
Select Action
Case Panel.ACTION_DOWN
' Your code for DOWN action
Case Panel.ACTION_MOVE
' Your code for MOVE action
Case Panel.ACTION_UP
' Your code for UP action
End Select
End Sub
10 Basic Language 220 B4i Beginner's Guide
10.7 Libraries
- If no, download the library, unzip it and copy the <LibraryName>.xml file to the additional
libraries folder.
- Right click in the Lib area and click on and check the library in the list
to select it.
The standard B4i libraries are saved in the Libraries folder in the B4i program folder.
Normally in: C:\Program Files\Anywhere Software\B4i\Libraries
For the additional libraries it is useful to setup a special folder to save them somewhere else.
For example: C:\B4i\AdditionalLibraries
When you install a new version of B4i, all standard libraries are automatically updated, but the
additional libraries are not included. The advantage of the special folder is that you don't need to
care about them because this folder is not affected when you install the new version of B4i.
The additional libraries are not systematically updated with new version of B4i.
When the IDE starts, it looks first for the available libraries in the Libraries folder of B4i and then
in the folder for the additional libraries.
10 Basic Language 221 B4i Beginner's Guide
If you setup a special additional libraries folder you must specify it in the IDE.
A
list
of
the
offi
cial
and
add
itio
nal
libr
arie
s
wit
h
link
s to
the
rele
van
t
forum threads is shown
in B4i Libraries.
If you get this message, means that you forgot to check the specified library in the Lib Tab list!
In the program line where the error occurs the unknown object is highlighted in red.
10 Basic Language 223 B4i Beginner's Guide
B4i allows string manipulations like other Basic languages but with some differences.
Number formatting, display numbers as strings with different formats, there are two keywords:
NumberFormat(Number As Double, MinimumIntegers As Int, MaximumFractions As Int)
NumberFormat(12345.6789, 0, 2) = 12,345.68
NumberFormat(1, 3 ,0) = 001
NumberFormat(Value, 3 ,0) variables can be used.
NumberFormat(Value + 10, 3 ,0) arithmetic operations can be used.
NumberFormat((lblScore.Text + 10), 0, 0) if one variable is a string add parentheses.
10.9 Timers
A 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 events and messages.
A timer has:
Two methods.
o Initialize Initializes the timer with two parameters, the EventName and the
interval.
Timer1.Initialize(EventName As String, Interval As Long)
Ex: Timer1.Initialize("Timer1", 1000)
Two properties.
o Interval Sets the timer interval in milli-seconds.
Timer1. Interval = Interval
Ex: Timer1.Interval = 1000, 1 second
One Event
o Tick The Tick routine is called every time interval.
Ex: Sub Timer1_Tick
Sub Process_Globals
Public Timer1 As Timer
But it must be initialized in the Application_Start routine in the module where the timer tick
event routine is used.
10.10 Files
Many applications require access to a persistent storage. The two most common storage types are
files and databases.
The predefined keyword File has a number of functions for working with files.
Files locations - There are several important locations where you can read or write files.
File.DirAssets
Returns a reference to the files added with the file manager in the IDE.
These files are read-only.
File.DirDocuments
The documents folder should only be used to store user generated content. It is possible to make this
folder sharable through iTunes.
This folder is backed up by iTunes automatically.
File.DirLibrary
The place for any non-user generated persistent files.
This folder is backed up by iTunes automatically.
You can create a subfolder named Caches, Files under that folder will not be backed up.
File.DirTemp
A temporary folder. Files in this folder are not backed up by iTunes and may be deleted from time
to time.
The File object includes several methods for writing to files and reading from files.
10.10.2 Filenames
Example : MyFile.txt
10.10.3 Subfolders
To access the subfolder you should add the subfolder name to the folder name with "/" in-between.
ImageView1.Bitmap = LoadBitmap(File.DirDocuments & "/Pictures", "test1.png")
Or add the subfolder name before the filename with "/" in-between.
ImageView1.Bitmap = LoadBitmap(File.DirDocuments, "Pictures/test1.png")
Text encoding or character encoding consists of a code that pairs each character from a given
repertoire with something else. Other terms like character set (charset), and sometimes character
map or code page are used almost interchangeably (source Wikipedia).
In Windows the most common character sets are ASCII and ANSI.
ASCII includes definitions for 128 characters, 33 are non-printing control characters (now
mostly obsolete) that affect how text and space is processed.
ANSI, Windows-1252 or CP-1252 is a character encoding of the Latin alphabet, used by
default in the legacy components of Microsoft Windows in English and some other Western
languages with 256 definitions (one byte). The first 128 characters are the same as in the
ASCII encoding.
Many files generated by Windows programs are encoded with the ANSI character-set in western
countries. For example: Excel csv files, Notepad files by default.
But with Notepad, files can be saved with UTF-8 encoding.
To read Windows files encoded with ANSI you should use the Windows-1252 character-set.
If you need to write files for use with Windows you should also use the Windows-1252 character-
set.
Another difference between Windows and iOS (Android also) is the end of line character:
iOS, only the LF (Line Feed) character Chr(10) is added at the end of a line.
Windows, two characters CR (Carriage Return Chr(13)) and LF Chr(10) are added at the
end of a line. If you need to write files for Windows you must add CR yourself.
To read or write files with a different encoding you must use File.ReadString2 or File.WriteString2.
Even for reading csv files.
10 Basic Language 231 B4i Beginner's Guide
Or
Read the whole file with File.ReadString2 and "Windows-1252" encoding.
Save it back with File.WriteString2 with the standard iOS encoding.
Read the file with LoadCSV or LoadCSV2 from the iStringUtils library.
File.WriteString(txt)
When you save a file with NotePad three additional bytes are added.
These bytes are called BOM characters (Byte Order Mark).
In UTF-8 they are represented by this byte sequence: 0xEF,0xBB,0xBF.
A text editor or web browser interpreting the text as Windows-1252 will display the
characters .
To avoid this you can use Notepad++ instead of NotePad and use Encode in UTF-8 without BOM.
Another possibility to change a text from Windows-1252 to UTF-8 is to use the code below.
10.11 Lists
Lists are often used and many examples can be found in code examples:
StringUtils LoadCSV, SaveCSV
DBUtils module InsertMaps, UpdateRecord, ExecuteMemoryTable, ExecuteSpinner,
ExecuteListView, ExecuteHtml, ExecuteJSON
Charts module to hold different variables.
Initialize2 (SomeArray)
Initializes a list with the given values. This method should be used to convert arrays to lists.
Note that if you pass a list to this method then both objects will share the same list, and if
you pass an array the list will be of a fixed size.
Meaning that you cannot later add or remove items.
Example 1:
Dim List1 As List
List1.Initialize2(Array As Int(1, 2, 3, 4, 5))
Example 2:
Dim List1 As List
Dim SomeArray(10) As String
' Fill the array
List1.Initialize2(SomeArray)
You can add and remove items from a list and it will change its size accordingly.
With either:
Add (item As Object) .
Adds a value at the end of the list.
List1.Add(Value)
Use the Get method to get an item from the list with:
Get(Index As Int)
number = List1.Get(i)
You can use a For loop to iterate over all the values:
For i = 0 To List1.Size - 1
Dim number As Int
number = List1.Get(i)
...
Next
A List can be sorted (the items must all be numbers or strings) with:
Sort(Ascending As Boolean)
List1.Sort(True) sort ascending
List1.Sort(False) sort descending
SortCaseInsensitive(Ascending As Boolean)
10.12 Maps
The keys are unique. Which means that if you add a key/value pair (entry) and the collection
already holds an entry with the same key, the previous entry will be removed from the map.
The key should be a string or a number. The value can be any type of object.
Get an entry:
Get(Key As Object)
Language = Map1.Get("Language")
Check if a Map contains an entry, tests whether there is an entry with the given key:
ContainsKey(Key As Object)
If Map1.ContainsKey("Language") Then
Msgbox("There is already an entry with this key !", "ATTENTION")
Return
End If
Remove an entry:
Remove(Key As Object)
Map1.Remove("Language")
B4A
The different screens are manly managed with Activities in separate modules, or on Panels
managed in the Main Activity or a mix of both.
11.2 Panel
B4i
Panels don’t have a background bitmap.
But you can draw onto a Panel with a Canvas.
If a Panel, without event routines, covers other views the events are NOT submitted to the
underlying views. In B4A they are!
If you want to submit them, you must set the UserInteractionEnabled property to False:
Panel1.UserInteractionEnabled = False
B4A
Panels have a background bitmap.
It is also possible to draw onto a Panel with a Canvas.
If a Panel, without event routines, covers other views the events ARE submitted to the underlying
views. In B4i they are NOT!
To avoid this, one solution is to add an empty event routine.
11.3 Canvas
When you use a Canvas, you need to refresh the drawing to make it visible.
B4i
You refresh the Canvas with Canvas.Refresh.
B4A
You refresh the Canvas view like Panel1.Invalidate.
In B4A you can also refresh only a part of the Canvas view, limited by a rectangle Rect, with
Invalidate2(Rect).
B4A
B4A has only one view to enter text, single line or multiline:
EditText Can be single line or multiline.
11.5 ScrollViews
B4i
ScrollView Scrolls in both directions.
It’s equivalent to ScrollView2D in B4A.
Can optionally scroll the whole width or the whole height with one swipe.
Change the internal panel size.
ScrollView1.ContentHeight
ScrollView1.ContentWidth
B4A
ScrollView Scrolls only in vertical direction.
HorizontalScrollView Scrolls only in horizontal direction.
ScrollView2D Scrolls in both directions.
Change the internal panel size.
ScrollView1.Panel.Height
HorizontalScrollView1.Panel.Width
ScrollView2D1.Panel.Height
ScrollView2D1.Panel.Widht
B4A
Spinner One line visible and extended with a click onto the Spinner.
11.7 ListView
B4i B4A
Doesn’t exist. Shows a list.
You can use the CustomListView class instead.
11.8 RadioButton
B4i B4A
Doesn’t exist. Exist
11 Differences B4A <> B4i 238 B4i Beginner's Guide
B4A
CheckBox Shows a check box with two states.
11.10 SegmentedControl
B4i
Shows several buttons side by side for selection.
B4A
Doesn’t exist
11.11 Stepper
B4i
B4A
Doesn’t exist
B4A
The Background is a Drawable.
ColorDrawable same as Color in B4i.
GradientDrawable doesn’t exist in B4i
BitmapDrawable doesn’t exist in B4i
StateListDrawable doesn’t exist in B4i
11 Differences B4A <> B4i 239 B4i Beginner's Guide
Example:
Msgbox2("MsgDelete", "Delete entry", "Do you really want to delete the entry ?",
Array As String("Yes", "No"))
B4A
Modal object.
The program stops at the line where MsgBox is called and waits for the user input.
Msgbox(Message As String, Title As String)
Answer = Msgbox2(Message As String, Title As String, Positive As String, Cancel As
String, Negative As String, Icon As Bitmap)
Example:
Answer = Msgbox2("MsgDelete", "Do you really want to delete the entry ?", "Delete
entry", "Yes", "", "No", Null))
11 Differences B4A <> B4i 240 B4i Beginner's Guide
B4A
In B4A you can use another object called Cursor, the Cursor object doesn’t exist in B4i.
It is possible to position the Cursor at a given item with Cursor.Position = i
Code to go through the results
Private Curs As Cursor
Private i As Int
For i = 0 To Curs.RowCount - 1
Curs.Position = i
' your code
Next
B4A
TextSize is a property which can be changed directly.
lblLabel1.TextSize = 20
11 Differences B4A <> B4i 241 B4i Beginner's Guide
B4A
Predefined folders:
DirAssets
Same as B4i
DirInternal
Returns the folder in the device internal storage that is used to save application private data.
DirInternalCache
Returns the folder in the device internal storage that is used to save application cache data.
This data will be deleted automatically when the device runs low on storage.
DirDefaultExternal
Returns the application default external folder which is based on the package name.
The folder is created if needed.
DirRootExternal
Returns the root folder of the external storage media.
If the device has an intenal sdcard, then DirRooiExternal points to this one and not to an
external sdcard.
11.18 Map
Example to go through the keys:
B4i
No GetKeyAt method.
'B4i method
For Each k As String In myMap.Keys
kd = myMap.Get(k)
B4A
GetKeyAt exists.
'B4A method
For k = myMap.Size - 1 To 0 Step -1
kd = myMap.GetKeyAt(k)
11 Differences B4A <> B4i 242 B4i Beginner's Guide
11.19 Regex
B4i
Regex.Split doesn’t allow “”(empty string) as the split string
B4A
Regex.Split allows “” (empty string) as the split string
12 User interfaces 243 B4i Beginner's Guide
12 User Interfaces
In this chapter several example programs are explained with code examples.
All projects are saved in the SourceCode folder shipped with the guide.
Almost all iOS apps use at least some of the UI components defined by the UIKit framework.
Knowing the names, roles, and capabilities of these basic components helps you make informed
decisions as you design the UI of your app.
12.1 Bars
On top of the screen the status bar displays important information about the device and the current
environment (shown below on iPhone).
12.1.2 NavigationController
The NavigationController manages two bars:
The NavigationBar on the top of the screen, just below the StatusBar.
The ToolBar on the bottom of the screen.
12.1.2.1 NavigationBar
The NavigationBar is on the top of the screen just below the StatusBar.
Title.
It is good practice to add a title, which is displayed in the middle of the NavigationBar to
inform the user of the purpose of the selected page.
TopRightButtons.
On the right side you can add buttons for different functions.
12.1.2.1.1 TopRightButtons
In the NavigationBar you can add buttons on the right side of the bar.
12.1.2.1.2 TopLeftButtons
Normally the upper left button is used as a back button allowing to move back to the previous page.
You can also use it for other buttons, but be careful because most users expect the back button
there.
To hide the back button you must set the HideBackButton property to:
in the Designer
in the code Page.HideBackButton = True.
12 User interfaces 246 B4i Beginner's Guide
12.1.2.2 ToolBar
The optional ToolBar is displayed at the bottom of the screen.
The default value of the Page.ToolBarVisible property is False, so you need to set it to True to
display it Page.ToolBarVisible = True.
12.1.2.3 BarButtons
The Buttons on the NavigationBar and on the ToolBar are BarButtons.
o If you add two buttons they are positioned one on the left side and the other on the
right side.
The Designer adds automatically a FLEXIBLE_SPACE button in between.
o If you want two buttons, one in the middle and the second one on the right side you
must add a FLEXIBLE_SPACE button as the first button.
o If you add three buttons one on the left, the second in the middle and the third on the
right, the Designer adds automatically two FLEXIBLE_SPACE buttons in between.
12 User interfaces 248 B4i Beginner's Guide
o Example:
Code
o BarButtons added in the code are
placed side by side starting on the
left side.
First
First Second
First Second Third
o For two buttons one on the left
and the other on the right side you
must add a FLEXIBLE_SPACE button between the two others.
o Same for three BarButtons Left, Middle, Right you must add two
FLEXIBLE_SPACE button between the others.
First
First □ Second
First □ Second □ Third
o Example with two buttons one in the middle and one on the right side:
' Dim the buttons
Dim bbt1, bbt2, bbt3 As BarButton
' Initialize the buttons
bbt1.InitializeSystem(bbt2.ITEM_FLEXIBLE_SPACE, "")
bbt2.InitializeText("Page 2", "Page2")
bbt3.InitializeText("Page 3", "Page3)
' Add the buttons onto Page1
Page1.ToolbarButtons.AddAll(Array As Object(bbt1, bbt2, bbt3))
12 User interfaces 249 B4i Beginner's Guide
Example:
Dim BarButton1 As BarButton
BarButton1.InitializeText("Page 1", "Page1")
Example:
Dim BarButton1 As BarButton
BarButton1.InitializeBitmap(LoadBitmap(File.DirAssets, "image.png"), "Image1")
One bitmap is used, the color changes automatically when the button is touched.
You may provide several image files for the different screen resolutions (scales):
Pixel size Image file name
60 x 60 image.png
120 x 120 image @2x.png
180 x 180 image @3x.png
In the initialization, don’t add @2x to the files, iOS loads the correct file with the generic file name
according to the device scale.
Example:
Dim BarButton1 As BarButton
BarButton1.InitializeSystem(BarButton1.ITEM_BOOKMARKS, "BookMark")
12 User interfaces 250 B4i Beginner's Guide
Example:
Dim BarButton1 As BarButton
BarButton1.InitializeCustom("Page 1", "Page1") ??????
12.1.2.4 Tips
Be careful with the space taken by the title and the buttons in the NavigationBar.
Don’t use more than 5 BarButtons in the ToolBar.
Leave enough place between Text BarButton.
12 User interfaces 252 B4i Beginner's Guide
12.2 SegmentedControl
A segmented control is a horizontal control made of multiple segments, each segment functioning
as a discrete button.
You must:
Dim it in Process_Globals
Private sgcButtons As SegmentedControl
Initialize it in Application_Start
sgcButtons.Initialize("sgcButtons")
' Add the button items, these texts will be displayed in the buttons.
sgcButtons.SetItems(Array As String("<<", "<", ">", ">>"))
' We set Momentary = True to not show the selected button
sgcButtons.Momentary = True
Add it to the page in Page1_Resize, to ensure that the current size is known.
' sgcButtons is added here because Widht and Height
' are known only from here
Private Sub Page1_Resize(Width As Int, Height As Int)
Page3.RootPanel.AddView(sgcButtons, 10, sgcFlowers.Top + sgcFlowers.Height +
10, 100%x - 20, 40)
End Sub
The result:
12 User interfaces 254 B4i Beginner's Guide
12.3 ActionSheet
Action sheets display a set of buttons representing several alternative choices to complete a task
initiated by the user.
An action sheet:
Appears as the result of a user action
Displays two or more buttons
In a horizontally compact environment, include a Cancel button so that users can easily and
safely abandon the task. Place the Cancel button at the bottom of the action sheet to encourage
users to read through all the alternatives before making a choice.
In all environments, use red for the button that performs a potentially destructive action.
Display a red button at the top of the action sheet, because the closer to the top of the action sheet a
button is, the more eye-catching it is.
Avoid making users scroll an action sheet. If you include too many buttons in an action sheet,
users must scroll to see all their choices. This is a disconcerting experience for users, because they
must spend extra time to distinguish the choices. Also, it can be very difficult for users to scroll
without inadvertently tapping a button.
12 User interfaces 255 B4i Beginner's Guide
Although the first parameter of the initialization method enables you to provide a title for an action
sheet, iOS human interface guidelines recommend that you do not use a title.
Delete, DestructiveItem
Cancel button
12 User interfaces 256 B4i Beginner's Guide
Source code:
Dim: in Sub Process_Globals
Private ashTest1 As ActionSheet
Event routine:
Private Sub ashTest1_Click(Item As String)
Select Item
Case "Cancel"
Msgbox("'Cancel' clicked", "Editing")
Case "Add"
Msgbox("'Add' clicked", "Editing")
Case "Edit"
Msgbox("'Edit' clicked", "Editing")
Case "Insert"
Msgbox("'Insert' clicked", "Editing")
Case "Delete"
Msgbox2("msgDelete", "Dou you really want to delete the entry ?", "Editing", Array
("Yes", "No"))
End Select
End Sub
12 User interfaces 257 B4i Beginner's Guide
Message boxes, called Alerts in iOS, are called MsgBox in B4i like in B4A.
They are not exactly the same, the major difference is that B4i MsgBoxes are not modal views. This
means that the code continues after the calling of the MsgBox and not waiting on the user answer.
The answer must be handled in an event routine.
Example:
Msgbox("'Insert' clicked", "Editing")
Example:
Msgbox2("msgDelete", "Dou you really want to delete the entry ?", "Editing",
Array ("Yes", "No"))
The examples above are from the UINavBar project on Page 2, Edit ToolBar.
12 User interfaces 258 B4i Beginner's Guide
The program has no other function than to show different user interface possibilities.
NavigationBar
ToolBar
SegmentedControl
ActionSheet
Alerts MsgBox / MsgBox2
The user interface in this project is not coherent because of the use of too many different user
interface objects, but the purpose is to show different possibilities in one project not showing best
practice.
The program has three pages, with different user interface examples.
The pictures are just there to show the page changes (pictures taken during my mountain hikes).
Page 1
NavigationBar Only the title.
ToolBar Two BarButtons to navigate.
Page 2
NavigationBar Title and back button.
ToolBar Two BarButtons activating the ActionSheets.
Other Two ActionSheets, Pages to navigate.
Page 3
NavigationBar Title, back button and a top right button.
ToolBar No ToolBar.
Other Two SegmentedControls.
12 User interfaces 259 B4i Beginner's Guide
Some explanations:
Page 1:
Nothing special, only the two navigation buttons.
Page 2:
The Pages button shows an ActionSheet to navigate.
The Edit button shows another ActionSheet.
Page 3:
No ToolBar for the navigation, only the return button.
Note that with the return button you return to the calling page, either Page 1 or Page 2.
The Action button only shows the use of a TopRightButton.
ToolBar and TopRightButton event are handled in the same BarButtonClick_Click event routine.
12.6 TabBarController
Sub Process_Globals
Public App As Application
Public TabControl As TabBarController
Private Page1, Page2, Page3 As Page
End Sub
12 User interfaces 261 B4i Beginner's Guide
One bitmap for the unselected state and the second one for the selected state.
Example bitmaps, with a size of 30 x 30 pixels for a scale of 1.
The black frames are not part of the images, the white parts are transparent:
Unselected Selected
The color has no importance, only the Alpha value is considered by the system.
The color of the non-transparent part is defined by the system like this:
You may provide several image files for the different screen resolutions (scales):
Pixel size Image file name
30 x 30 btnCH0.png
60 x 60 btnCH0@2x.png
90 x 90 btnCH0@3x.png
Initialization:
iOS loads the correct file with the generic file name according to the device scale, you must not
add @2x to the files.
tbi.Initialize("Countries", LoadBitmap(File.DirAssets, "btnCH0.png"), _
LoadBitmap(File.DirAssets, "btnCH1.png"))
12.6.1.4 Tips
Don’t set more than 5 items in the TabBar on phones.
On big devices more items can be added.
Be aware to leave enough place between text items.
12 User interfaces 264 B4i Beginner's Guide
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
Page1.Initialize("Page1")
Page1.Title = "Page 1"
Page1.RootPanel.Color = Colors.White
Page1.RootPanel.LoadLayout("Main")
13 Debugging
Debugging is an important part when developing.
Breakpoints - You can mark lines of codes as breakpoints. This is done by pressing on the grey area
left 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 the
components life cycle and it can also show messages that are printed with the Log keyword. You
should press on the Connect button to connect to the device logs. Note that there is a Filter
checkbox. When it is checked you will only see messages related to your program. When it is
unchecked you will see all the messages running in the system. If you are encountering an error and
do not see any relevant message in the log, it is worth unchecking the filter option and looking for
an error message.
Note that the log is maintained by the device. When you connect to a device you will also see
previous messages.
Debug Toolbar:
13.1.1 Run F5
13.1.2 Step In F8
Click on .
The debugger executes the next line,
Sub New in this case.
If the current line is a sub calling line the debugger executes the code in this subroutine and jumps
to the line after the calling line.
Click on .
The debugger executes the code in
New and jumps directly to the next
line which is
End Sub of Application_Start.
13 Debugging 268 B4i Beginner's Guide
If the current line is a sub calling line the debugger executes the code in this subroutine and jumps
to the line after the calling line.
Click on .
The debugger executes the rest of
the code in the subroutine and jumps
to the next line which is
End Sub of Application_Start.
13.1.5 Stop
In the debug window we have (example with the SecondProgram, and a breakpoint in line 72:
When you change the code the button border changes to red.
To update the code click on the button or hit Ctrl + S.
When you click on one of the lines the cursor jumps to that line.
13 Debugging 270 B4i Beginner's Guide
The Watch window allows to check more complex functions for testing and debugging.
Number1 + Number2
Click on to show the result on top of
the list.
As we left the two Log lines in the code we still see the
values of Number1 and Number2.
Click on to remove the watch functions. This removes all the functions.
Shows all variables and objects in the list ordered by alphabetical order.
Examples:
Number1
Shows the current value (8).
lblNumber1
lblNumber1
Number1
13 Debugging 272 B4i Beginner's Guide
13.3 Breakpoints
One important feature to make debugging easier are breakpoints. You can set breakpoint almost
wherever you want in the code.
Breakpoints, in Process_Globals are ignored.
Clicking on a line in the left margin adds a breakpoint. When the program is running it stops at the
first encountered breakpoint.
Run the program, the program stops at the breakpoint and the IDE looks like below. The breakpoint
line is highlighted in yellow.
Click on .
The program jumps to the next line.
Click on .
You see that the value of
Number1 has changed.
Click on again.
The program jumps to the next line.
Click on .
You see that the value of
Number2 has changed.
When you are using the program the two new values will
be shown every time the program runs the New routine.
13 Debugging 275 B4i Beginner's Guide
It is possible to change the code in the Debugger and see the new behavior without restarting the
program.
Still with SecondProgram and the two Logs and the breakpoint in line 73.
Using the program we see now that the numbers can be between 1 and 19.
14 Example programs 276 B4i Beginner's Guide
14 Example programs
In this chapter several example program are explained with code examples.
All projects are saved in the SourceCode folder shipped with the guide.
No programs yet.
15 Graphics / Drawing 277 B4i Beginner's Guide
15 Graphics / Drawing
15.1 Overview
A Canvas must be dimed in Process_Globals and initialized in Page_Resize before it can be used.
Example:
Sub Process_Globals
Private pnlLayout0 As Panel
Private cvsLayout0 As Canvas
And then
Private Sub Page1_Resize(Width As Int, Height As Int)
cvsLayer0.Initialize(pnlLayer0)
DrawText (Text As String, x As Float, y As Float, Font1 As Font, Color As Int, Align1 As
Align).
Draws the given text.
Font1 = Font object
Align1 can be either : LEFT, CENTER or RIGHT
15.2 Coordinates
In iOS there is a distinction between the coordinates you specify in your drawing code and the pixels of the
underlying device. When using native drawing technologies such as Quartz, UIKit, and Core Animation, the
drawing coordinate space and the view’s coordinate space are both logical coordinate spaces, with
distances measured in points. These logical coordinate systems are decoupled from the device coordinate
space used by the system frameworks to manage the pixels onscreen.
The system automatically maps points in the view’s coordinate space to pixels in the device coordinate
space, but this mapping is not always one-to-one. This behavior leads to an important fact that you should
always remember:
The purpose of using points (and the logical coordinate system) is to provide a consistent size of output that
is device independent. For most purposes, the actual size of a point is irrelevant. The goal of points is to
provide a relatively consistent scale that you can use in your code to specify the size and position of views
and rendered content. How points are actually mapped to pixels is a detail that is handled by the system
frameworks. For example, on a device with a high-resolution screen, a line that is one point wide may
actually result in a line that is two physical pixels wide. The result is that if you draw the same content on two
similar devices, with only one of them having a high-resolution screen, the content appears to be about the
same size on both devices.
B4i B4A
1 Point = 1 dip (device independent pixel)
B4i B4A
Coordinates Point Pixel
View dimensions Point Pixel
Drawing coordinates Point Pixel
Adding a view AddView(10, 10, 150, 50) AddView(10dip, 10dip, 150dip,
50dip)
Standard dpi 160 16’
(dots per inch)
GetDeviceLayoutValues Example 320 dpi screen
Scale Always 1 2
NonnormalizedScale 2 ---
Width Point Pixel
Height Point Pixel
1 Pixel 1 Point / NonnormalizedScale ---
1 Point --- 1 Pixel * Scale
15 Graphics / Drawing 280 B4i Beginner's Guide
15.3 Transparency
There are a few differences between B4A and B4i with transparency.
The test project, Transparency, is in the SourceCode folder shipped with the Beginner’s Guide.
Let’s consider three examples with a Panel defined in the Designer and a Canvas for each and the
same drawing functions:
cvsTest1.DrawColor(Colors.DarkGray)
cvsTest1.DrawCircle(100, 60, 50, Colors.Transparent, True, 1)
cvsTest1.DrawLine(20, 120, 200, 120, Colors.Red, 4)
cvsTest1.Refresh
If we want to draw on different views at the same time we need one Canvas for each view.
In the example program we'll use several drawing functions and draw onto the Activity and onto a
Panel pnlGraph defined in the 'main' layout file. Here we need two canvases.
15 Graphics / Drawing 282 B4i Beginner's Guide
Sub Process_Globals
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
And we initialize the two Canvases and call the Drawing routine.
We need to initialize the canvases in the Page1_Resize routine and not in Application_Start to make
sure that the sizes are correct!
Drawing
End Sub
15 Graphics / Drawing 283 B4i Beginner's Guide
Then we draw a horizontal line onto pnlGraph with the same coordinates:
The coordinates are relative to the upper left corner of the view we draw on, the Panel pnlGraph in
this case.
Then we draw a filled rectangle onto pnlGraph with the same coordinates:
We don't need to define nor initialize a new rectangle because the coordinates are the same so we
use the same Rect object.
Then we draw a filled circle with a border with a different color on the panel.
There is no direct function to draw a filled circle with a border with a different colors.
So we first draw the filled circle and then the circle border in two steps.
Instead of using fixed values like 220 we can also use variables like in the code below.
When a same value is used several times it's better to use variables because if you need to change
the value you change it only once the value of the variable all the rest is changed automatically by
the variable.
And we draw a cross on the reference point to show where it is and how the alignment does work.
The function is DrawTextRotated, it's the same as DrawText but with an additional parameter
Degrees, the rotation angle.
Instead of using fixed values in the routine we define three variables:
refX and refY the coordinates of the reference point
hl the half of the cross line length
And at the end we need to ‘refresh’ the canvases to show the result.
cvsPage.Refresh
cvsGraph.Refresh
15 Graphics / Drawing 287 B4i Beginner's Guide
In the second drawing program, SimpleDrawFunctions, we use the other common drawing
functions.
The program has no other purpose than show what can be done with drawings.
The program has four Panels which we use as layers, one for the background and three layers with
three Switches allowing to show or hide the different layers.
The background layer has an image, Layer(0) has a grey background and the two other layers have
a transparent background.
You can play with the switches to observe the different combinations of visible and hidden layers.
Touching the screen and moving the finger moves the blue
and transparent circles on layer(0).
15 Graphics / Drawing 289 B4i Beginner's Guide
You can play with the buttons to show the different combinations of visible and hidden layers.
15 Graphics / Drawing 290 B4i Beginner's Guide
Touching the screen with the finger and moving it, moves
the blue and transparent circles.
Note that we use arrays of views for the three layer panels and the canvases.
Sub Process_Globals
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
NavControl.ShowPage(Page1)
cvsBackground.Initialize(pnlBackground)
Drawing
End Sub
Sub Drawing
' draw the background image
rectBG.Initialize(0, 0, pnlBackground.Width, pnlBackground.Height)
cvsBackground.DrawBitmap(bmpBackground, rectBG)
cvsBackground.Refresh
xc = 90
yc = 160
r1 = 70
cvsLayer(1).DrawCircle(xc, yc, r1, Colors.Green, False, 2)
r1 = 60
cvsLayer(0).DrawCircle(xc, yc, r1, Colors.RGB(0, 128, 255), True, 3)
r2 = 50
cvsLayer(0).DrawCircle(xc, yc, r2, Colors.Transparent, True, 1)
15 Graphics / Drawing 293 B4i Beginner's Guide
x1 = 10
y1 = 10
x2 = 150
y2 = 20
cvsLayer(2).DrawLine(x1, y1, x2, y2, Colors.Red, 1)
y1 = 30
y2 = 30
cvsLayer(2).DrawLine(x1, y1, x2, y2, Colors.Green, 0.99)
y1 = 40
y2 = 50
cvsLayer(2).DrawLine(x1, y1, x2, y2, Colors.Yellow, 0.99)
y1 = 60
y2 = 70
cvsLayer(2).DrawLine(x1, y1, x2, y2, Colors.RGB(0, 128, 255), 5)
x1 = 220
y1 = 40
cvsLayer(2).DrawText("Rose", x1, y1, Font.CreateNew(20), Colors.Red, "LEFT")
rect1.Initialize(x1, y1, x1 + 2, y1 + 2)
cvsLayer(2).DrawRect(rect1, Colors.Red, True, 1)
y1 = 70
cvsLayer(2).DrawText("Rose", x1, y1, Font.CreateNew(20), Colors.Red, "CENTER")
rect1.Initialize(x1, y1, x1 + 2, y1 + 2)
cvsLayer(2).DrawRect(rect1, Colors.Red, True, 1)
y1 = 100
cvsLayer(2).DrawText("Rose", x1, y1, Font.CreateNew(20), Colors.Red, "RIGHT")
rect1.Initialize(x1, y1, x1 + 2, y1 + 2)
cvsLayer(2).DrawRect(rect1, Colors.Red, True, 1)
Looking closer on the displayed texts we see the reference point for each text.
cvsLayer(2).DrawText("Rose", x1, y1, Font.CreateNew(20), Colors.Red, "LEFT")
rect1.Initialize(x1, y1, x1 + 2, y1 + 2)
cvsLayer(2).DrawRect(rect1, Colors.Red, True, 1)
LEFT alignment.
CENTER alignment.
RIGHT alignment.
swt = Sender
index = swt.Tag
pnlLayer(index).Visible = Value
End Sub
15 Graphics / Drawing 295 B4i Beginner's Guide
16 Help Tools
To find answers to questions about B4i the following tools are very useful.
In the upper right corner you find the search box for the forum.
The function shows you the posts that match your request.
You can then filter the search with the buttons on the left.
Example: Click on
This program shows xml help files. It was originally written by Andrew Graham (agrham) for B4A.
I modified it, with Andrews’ agreement, to show B4A, B4J, B4i and B4R xml help files.
On top we find:
Select an object.
Select a property.
Select a standard library.
Select an additional library.
Search for a given text.
Closes B4xHelp
Link to the B4i / B4A forum.
Link to Android documentation.
Link to iOS documentation.
B4A help files.
B4i help files.
B4J help files.
B4R help files.
16 Tools 300 B4i Beginner's Guide
Standard libraries
Once selected the directory is saved for the next start of the program.
16 Tools 301 B4i Beginner's Guide
Additional libraries.
Example:
Selected library: iCore
Enter DrawRect
If you cannot find the answer with the previous tools you can ask the question in the forum.
Example:
Then click on .
16 Tools 304 B4i Beginner's Guide
The editor:
select Quote.
select Code.
Copy the code from the IDE, or enter it, and click on .
The code is added between the CODE tags [CODE][/CODE] and formatted.
You can also add the CODE tags and the code directly in the editor.
16.5.4 Links
17 Code snippets
Dim wv As WebView
wv.Initialize("wv")
Dim no As NativeObject = wv
no.GetField("scrollView").SetField("showsHorizontalScrollIndicator", False)
no.GetField("scrollView").SetField("showsVerticalScrollIndicator", False)
'value between 0 to 1
Sub SetScreenBrightness (value As Float)
Dim no As NativeObject
no.Initialize("UIScreen").RunMethod("mainScreen",Null).SetField("brightness", value)
End Sub
Dim b As Button
b.Initialize("b", b.STYLE_SYSTEM)
b.Text = "Click me"
b.Width = 100
b.Height = 50
Dim no As NativeObject = TextField1
no.SetField("inputAccessoryView", b)