B4X: ABMaterials B4JS – 07 The UI Connection (part 2)


This is the second part of the UI (ABMaterial) Connection. I wanted to do this one before releasing ABM 4.25 because it contains some important concepts on defining the events for B4JS in an ABMPage.

I’ve created a B4JS Demo that includes the source code for all the tutorials (so far). It will be included in the download zip.

One of the major advantages of B4JS is that you can check a lot of the users input before heading to the server. And because we have some events (like KeyDown, KeyUp) that we do not have on the server side, we can even do some ‘masking’.

This example makes such a mask for a credit card (every 4 chars a space is inserted and a check is done). It is not finished (e.g. it does not take into account if the user puts its cursor in the middle), but it shows some major concepts of B4JS.


Lets dive into the B4X code:

The B4JS class B4JSInputChecker:

'Class module
Sub Class_Globals
   Private Page As ABMPage 'ignore, just to be able to run ABMPage functions
   Private ToastID As Int
   Private ABM As ABMaterial 'ignore, just to be able to use ABM constants
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub InitializeB4JS

End Sub

public Sub InputDown(Key As String) As Boolean
   'Log("Down key: " &amp; Key)
   Dim cardInp As ABMInput 'ignore that it is not initialized, you can't initialize one in B4JS anyway
   cardInp.B4JSUniqueKey = "cardInp001"
   Dim CardNumber As String = cardInp.B4JSText
   If Key = "Backspace" Then
       If CardNumber.SubString2(0,CardNumber.Length-1).EndsWith(" ") Then
           CardNumber = CardNumber.SubString2(0,CardNumber.Length - 2)
           cardInp.B4JSText = CardNumber
           CheckCard(CardNumber.Replace(" ", ""))
           ' consume the event
           Return True
       End If
       ' let the Keydown do its thing
       Return False
   End If

   If CardNumber.Length = 19 Then
       CheckCard(CardNumber.Replace(" ", ""))
       Return True
   End If

   If Not(IsNumber(Key)) Then
       ToastID = ToastID + 1
       Page.B4JSShowToast("InputToast" &amp; ToastID, "red", "Please only enter numbers!", 3000, False)
       ' consume the event
       Return True
   End If

   ' let the Keydown do its thing
   Return False
End Sub

public Sub InputUp(KeyCode As Int) As Boolean
   'Log("Up keycode: " &amp; KeyCode)

   Dim cardInp As ABMInput 'ignore that it is not initialized, you can't initialize one in B4JS anyway
   cardInp.B4JSUniqueKey = "cardInp001"
   Dim CardNumber As String = cardInp.B4JSText

   ' we down't want to raise it for the combination keys
   ' AltGraph, Shift, Ctrl, Alt
   Select Case KeyCode
       Case 16, 17, 18
           ' consume the event
           Return True
       Case 8 ' and for the backspace, jump out too: we do not want to re-append the space
           ' consume the event
           CheckCard(CardNumber.Replace(" ", ""))
           Return True
   End Select

   Select Case CardNumber.Length
       Case 4,9,14
           cardInp.B4JSText = CardNumber &amp; " "
   End Select

   'a valid 4012 8888 8888 1881
   CheckCard(CardNumber.Replace(" ", ""))

   ' consume the event
   Return True
End Sub

public Sub CheckCard(CardNumber As String)
   'a valid 4012 8888 8888 1881
   Dim isValid As Boolean = Page.B4JSRunInlineJavascriptMethod("validateCCNum", Array As Object(CardNumber.Replace(" ", "")))
   Dim btnCheck As ABMButton 'ignore
   btnCheck.B4JSUniqueKey = "btnCheck"
   ' for our setButtonCSS method we do need the real ID of the button.  We can get this with the Page.B4JSGetComponentIDFromUniqueID() method!
   Dim ID As String = Page.B4JSGetComponentIDFromUniqueID("btnCheck")
   If isValid Then
       btnCheck.B4JSEnabled = True
       Page.B4JSRunInlineJavascriptMethod("setButtonCSS", Array As String(ID, "background-color: #4caf50 !important"))
       btnCheck.B4JSEnabled = False
       Page.B4JSRunInlineJavascriptMethod("setButtonCSS", Array As String(ID, "background-color: #F44336 !important"))
   End If
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub InputGotFocus() As Boolean
   ToastID = ToastID + 1
   Page.B4JSShowToast("InputToast" &amp; ToastID, "red", "You are entering the Credit Card", 3000, False)
   ' consume the event
   Return True
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub InputLostFocus() As Boolean
   ToastID = ToastID + 1
   Page.B4JSShowToast("InputToast" &amp; ToastID, "red", "Leaving the Credit Card field...", 3000, False)
   ' consume the event
   Return True
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub CheckInput() As Boolean
   Dim switch1 As ABMSwitch  'ignore that it is not initialized, you can't initialize one in B4JS anyway
   switch1.B4JSUniqueKey = "switch001"

   Dim HasError As Boolean = False

   ToastID = ToastID + 1
   If Not(switch1.B4JSState) Then
       Page.B4JSShowToast("SwitchToast" &amp; ToastID, "green", "Please put the Switch to ON!", 3000, False)
       HasError = True
   End If

   ToastID = ToastID + 1
   Dim CheckBox1 As ABMCheckbox 'ignore that it is not initialized, you can't initialize one in B4JS anyway
   CheckBox1.B4JSUniqueKey = "CheckBox001"
   If Not(CheckBox1.B4JSState) Then
       Page.B4JSShowToast("CheckboxToast" &amp; ToastID, "green", "Please check the Checkbox!", 3000, False)
       HasError = True
   End If

   If HasError = False Then
       ToastID = ToastID + 1
       Page.B4JSShowToast("CheckboxInput" &amp; ToastID, "green", "All looks OK, well done!", 3000, False)
   End If
   ' consume the event
   Return True
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub SwitchClick() As Boolean
   Dim switch1 As ABMSwitch  'ignore that it is not initialized, you can't initialize one in B4JS anyway
   switch1.B4JSUniqueKey = "switch001"

   ToastID = ToastID + 1
   If switch1.B4JSState Then
       Page.B4JSShowToast("SwitchToast" &amp; ToastID, "green", "Switch is ON", 3000, False)
       Page.B4JSShowToast("SwitchToast" &amp; ToastID, "green", "Switch is OFF", 3000, False)
   End If
   ' consume the event
   Return True
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub CheckBoxClick() As Boolean
   Dim CheckBox1 As ABMCheckbox 'ignore that it is not initialized, you can't initialize one in B4JS anyway
   CheckBox1.B4JSUniqueKey = "CheckBox001"
   ToastID = ToastID + 1
   If CheckBox1.B4JSState Then
       Page.B4JSShowToast("CheckboxToast" &amp; ToastID, "green", "Checkbox ON", 3000, False)
       Page.B4JSShowToast("CheckboxToast" &amp; ToastID, "red", "Checkbox OFF", 3000, False)
   End If
   ' consume the event
   Return True
End Sub

' every method you want to call with a B4JSOn... call MUST return a boolean
public Sub RadioClick() As Boolean
   Dim Radio1 As ABMRadioGroup 'ignore that it is not initialized, you can't initialize one in B4JS anyway
   Radio1.B4JSUniqueKey = "Radio001"
   ToastID = ToastID + 1
   Page.B4JSShowToast("RadioToast" &amp; ToastID, "green", "Active Radio = " &amp;  Radio1.B4JSGetActive, 3000, False)
   ' example of setting the active radio
   'If Radio1.B4JSGetActive = 0 Then
   '   Radio1.B4JSSetActive(2)
   'End If
   Return True
End Sub

public Sub RangeOnChange(start As String, Stop As String, ConsumeEvent As Boolean) As Boolean
   Log("B4JS Start: " &amp; start)
   Log("B4JS Stop: " &amp; Stop)
   Return ConsumeEvent
End Sub

function setButtonCSS(id, val) {
   $('#' + id).attr('style', val);
#End If

And creating the components in ConnectPage():

public Sub ConnectPage()
   '   connecting the navigation bar

   page.Cell(1,1).AddComponent(ABMShared.BuildParagraph(page,"par1","This demo is practical example of B4JS. It uses the B4JSInputChecker B4JS class.") )

   ' input
   Dim cardInp As ABMInput
   cardInp.Initialize(page, "inp1", ABM.INPUT_TEXT, "Credit Card", False, "")
   cardInp.B4JSUniqueKey = "cardInp001"
   ' special case, it has to pass at least the pressed key (ABM.B4JS_PARAM_INPUTKEY or ABM.B4JS_PARAM_INPUTKEYCODE) to it!
   cardInp.B4JSOnKeyDown("B4JSInputChecker", "InputDown", Array As Object(ABM.B4JS_PARAM_INPUTKEY))
   cardInp.B4JSOnKeyUp("B4JSInputChecker", "InputUp", Array As Object(ABM.B4JS_PARAM_INPUTKEYCODE))
   ' some focus stuff
   cardInp.B4JSOnGotFocus("B4JSInputChecker", "InputGotFocus", Null)
   cardInp.B4JSOnLostFocus("B4JSInputChecker", "InputLostFocus", Null)

   ' switch
   Dim switch1 As ABMSwitch
   switch1.Initialize(page, "switch1", "ON", "OFF", False, "")
   switch1.B4JSUniqueKey = "switch001"
   switch1.B4JSOnClick("B4JSInputChecker", "SwitchClick", Null)

   ' checkbox
   Dim CheckBox1 As ABMCheckbox
   CheckBox1.Initialize(page, "CheckBox1", "B4JS Checkbox", False, "")
   CheckBox1.B4JSUniqueKey = "CheckBox001"
   CheckBox1.B4JSOnClick("B4JSInputChecker", "CheckBoxClick", Null)

   ' radiogroup
   Dim Radio1 As ABMRadioGroup
   Radio1.Initialize(page, "Radio1", "")
   Radio1.B4JSUniqueKey = "Radio001"
   Radio1.AddRadioButton("radio 0", True)
   Radio1.AddRadioButton("radio 1", True)
   Radio1.AddRadioButton("radio 2", True)
   Radio1.B4JSOnClick("B4JSInputChecker", "RadioClick", Null)

   ' range
   Dim range As ABMRange
   range.Initialize(page, "range", 10, 20, 0, 100, 1, "")
   range.B4JSUniqueKey = "range001"
   ' special case, it has to pass at least ABM.B4JS_PARAM_RANGESTART & ABM.B4JS_PARAM_RANGESTOP!

   range.B4JSOnChange("B4JSInputChecker", "RangeOnChange", Array As Object(ABM.B4JS_PARAM_RANGESTART, ABM.B4JS_PARAM_RANGESTOP, True))

   ' button
   Dim btnCheck As ABMButton
   btnCheck.InitializeFlat(page, "btnCheck", "", "", "Check", "red")
   btnCheck.Enabled = False
   btnCheck.B4JSUniqueKey = "btnCheck"
   btnCheck.B4JSOnClick("B4JSInputChecker", "CheckInput", Null)

   ' refresh the page
   ' Tell the browser we finished loading
   ' restoring the navigation bar position
End Sub

As you see, for every component we want to use in a B4JS class, we have to set the B4JSUniqueKey property.

We also define some events (B4JSOn…). You notice some of them have special parameters, e.g. the ABMInputs B4JSOnKeyDown event. This event MUST have at least the parameter ABM.B4JS_PARAM_INPUTKEY or ABM.B4JS_PARAM_INPUTKEYCODE to be able to work.

For the B4JSOnKeyDown event for example, we pass the ABM.B4JS_PARAM_INPUTKEY param. The order of the params is very important!

In our B4JS class, this is our method definition:

public Sub InputDown(Key As String) As Boolean<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>

Here ABM.B4JS_PARAM_INPUTKEY’s value will be put into the Key param.

You can add additional params (if needed) as for example is done in the range.B4JSOnChange event declaration.

This concludes the tutorial. ABM 4.25 is now available for download for all donators in the feedback app!


Click here to Donation and support ABMaterial


B4J: Creating a Star Rating component in ABMaterial


Michał asked me in the feedback app to implement some kind of Star Rating component. As this is not so commonly needed, I thought this could be another good example of an ABMCustomComponent. One can ‘hover’ over the stars to set its value or it can be set and retrieved by code.

I show you how to do it in ABMaterial 3.75 first with the new features (released soon), and will then explain what needs to be changed for previous versions.

So let’s get started!

1. We create a new standard class CompStarRating:

'Class module
Sub Class_Globals
Public ABMComp As ABMCustomComponent
Dim myInternalName As String
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(InternalPage As ABMPage, ID As String, radioName As String)
myInternalName = radioName
Dim CSS As String = $"
#half-stars-example .rating-group {
display: inline-flex;
#half-stars-example .rating__icon {
pointer-events: none;
/* This is an important part: we MUST override the Materialize CSS implementation of the the radio button! */
#half-stars-example .rating__input + label:before,
#half-stars-example .rating__input + label:after {
position: absolute !important;
left: -9999px !important;
#half-stars-example .rating__label {
cursor: pointer;
padding: 0 0.1em;
font-size: 2rem;
margin-top: 1rem;
#half-stars-example .rating__label--half {
padding-right: 0;
margin-right: -0.6em;
z-index: 2;
#half-stars-example .rating__icon--star {
color: orange;
#half-stars-example .rating__icon--none {
color: #eee;
#half-stars-example .rating__input--none:checked + .rating__label .rating__icon--none {
color: red;
#half-stars-example .rating__input:checked ~ .rating__label .rating__icon--star {
color: #ddd;
#half-stars-example .rating-group:hover .rating__label .rating__icon--star,
#half-stars-example .rating-group:hover .rating__label--half .rating__icon--star {
color: orange;
#half-stars-example .rating__input:hover ~ .rating__label .rating__icon--star,
#half-stars-example .rating__input:hover ~ .rating__label--half .rating__icon--star {
color: #ddd;
#half-stars-example .rating-group:hover .rating__input--none:not(:hover) + .rating__label .rating__icon--none {
color: #eee;
#half-stars-example .rating__input--none:hover + .rating__label .rating__icon--none {
color: red;
ABMComp.Initialize("ABMComp", Me, InternalPage, ID, CSS)
End Sub

Sub ABMComp_Build(InternalPage As ABMPage, internalID As String) As String
Return $"
<div id="half-stars-example">
<div id="${internalID}" class="rating-group"><input id="rating-0" class="rating__input rating__input--none" checked="checked" name="${myInternalName}" type="radio" value="0" />
<label class="rating__label" title="0 stars" for="rating-0"> </label>
<input id="rating-00" class="rating__input" type="radio" value="-1" />
<label class="rating__label rating__label--half" title="0.5 stars" for="rating-05"><i class="rating__icon rating__icon--star fa fa-star-half"></i></label>
<input id="rating-05" class="rating__input" name="${myInternalName}" type="radio" value="0.5" />
<label class="rating__label" title="1 star" for="rating-10"><i class="rating__icon rating__icon--star fa fa-star"></i></label>
<input id="rating-10" class="rating__input" name="${myInternalName}" type="radio" value="1" />
<label class="rating__label rating__label--half" title="1.5 stars" for="rating-15"><i class="rating__icon rating__icon--star fa fa-star-half"></i></label>
<input id="rating-15" class="rating__input" name="${myInternalName}" type="radio" value="1.5" />
<label class="rating__label" title="2 stars" for="rating-20"><i class="rating__icon rating__icon--star fa fa-star"></i></label>
<input id="rating-20" class="rating__input" name="${myInternalName}" type="radio" value="2" />
<label class="rating__label rating__label--half" title="2.5 stars" for="rating-25"><i class="rating__icon rating__icon--star fa fa-star-half"></i></label>
<input id="rating-25" class="rating__input" name="${myInternalName}" type="radio" value="2.5" />
<label class="rating__label" title="3 stars" for="rating-30"><i class="rating__icon rating__icon--star fa fa-star"></i></label>
<input id="rating-30" class="rating__input" name="${myInternalName}" type="radio" value="3" />
<label class="rating__label rating__label--half" title="3.5 stars" for="rating-35"><i class="rating__icon rating__icon--star fa fa-star-half"></i></label>
<input id="rating-35" class="rating__input" name="${myInternalName}" type="radio" value="3.5" />
<label class="rating__label" title="4 stars" for="rating-40"><i class="rating__icon rating__icon--star fa fa-star"></i></label>
<input id="rating-40" class="rating__input" name="${myInternalName}" type="radio" value="4" />
<label class="rating__label rating__label--half" title="4.5 stars" for="rating-45"><i class="rating__icon rating__icon--star fa fa-star-half"></i></label>
<input id="rating-45" class="rating__input" name="${myInternalName}" type="radio" value="4.5" />
<label class="rating__label" title="5 stars" for="rating-50"><i class="rating__icon rating__icon--star fa fa-star"></i></label>
<input id="rating-50" class="rating__input" name="${myInternalName}" type="radio" value="5" /></div>
End Sub

public Sub GetCurrentRating(InternalPage As ABMPage) As Double
Dim script As String = $"return $('input[name=${myInternalName}]:checked').val();"$
Dim ret As Future = InternalPage.ws.EvalWithResult(script, Null)

Return ret.Value
End Sub

public Sub SetCurrentRating(InternalPage As ABMPage, value As Double) {
Dim script As String = $" $('input[name=${myInternalName}][value="${value}"]').prop('checked', 'checked');"$
InternalPage.ws.Eval(script, Null)
End Sub

' Is useful to run some initalisation script.
Sub ABMComp_FirstRun(InternalPage As ABMPage, internalID As String)
Dim script As String = $""$
InternalPage.ws.Eval(script, Array As Object(ABMComp.ID))
' flush not needed, it's done in the refresh method in the lib
End Sub
' runs when a refresh is called
Sub ABMComp_Refresh(InternalPage As ABMPage, internalID As String)
Dim script As String = $""$
InternalPage.ws.Eval(script, Array As Object(ABMComp.ID))
End Sub
' do the stuff needed when the object is removed
Sub ABMComp_CleanUp(InternalPage As ABMPage, internalID As String)
End Sub

ABMaterial users will notice I have added the CSS directly into the component. By doing so, we do not need to use the page.AddExtraCSSFile method in the Page_Build() method. (you can still do it this way, and in some cases it may be better as this part can be big. And in the final version, compress it!). In ABMaterial before version 3.75, using AddExtraCSSFile is the only way possible.

The only difficult part in the CSS was I had to override Materialize CSS’s implementation of a radio button (the ‘circle’). So we had to get rid of it.

2. Now we can make a variable for our StarComponent in the page Class_Globals, as we want to be able to Set and Get the value:

Dim myRating As CompStarRating

3. In Page_Connect() we add our component and a couple of buttons:

myRating.Initialize(page, "myRating", "rating")

Dim btn As ABMButton
btn.InitializeFlat(page, "btn", "", "", "Get value", "")

Dim btn2 As ABMButton
btn2.InitializeFlat(page, "btn2", "", "", "Set 2.5 stars value", "")

4. And our Get and Set code in the buttons:

Sub btn_Clicked(Target As String)
Dim value As Double = myRating.GetCurrentRating(page)
End Sub

Sub btn2_Clicked(Target As String)
myRating.SetCurrentRating(page, 2.5)
End Sub

That is all! :)

Changes for versions of ABMaterial before 3.75

1. Save the CSS string into a text file (e.g. star.rating.css) and copy it to the /css/custom folder.
2. Remove the CSS param from ABMComp.Initialize(“ABMComp”, Me, InternalPage, ID, CSS)

ABMComp.Initialize("ABMComp", Me, InternalPage, ID) '<-- CSS param deleted

3. In Sub ABMComp_Build(InternalPage As ABMPage, internalID As String) As String remove the InteranlPage param:

Sub ABMComp_Build(internalID As String) As String

4. In Page_Build(), load the css file you created:



Click here to Donation and support ABMaterial

B4i: 1 … 2 … 3 … Ready … Go!

This weekend I’ve found some time to setup my testing environment for B4i, the latest brainchild of Anywhere Software. I must say, being a novice Mac user, setting everything up went very smooth.

The only parts I got into some trouble was my own fault, as I went though the setup tutorials, videos and Beginners Guide just a little bit to fast. Eager to get started, I skimmed through them and forgot some important steps.

First I paid my obligatory taxes to Apple: $99/year. (Programming for Android only sets you back with a one time fee of $25). Only a couple of minutes later, my account was activated.

One part that may have gone a bit to fast for a first time Apple developer was the creation of an App ID. As Erel had his system already setup when he made the video and could just pick an App ID, he did not show us how to create it in the first place. It is mentioned further in the post you can create a single wildcard App ID if you put a .* at the end, but this was not very clear from the tutorial. So, this is how I did it:

Click to enlarge
Click to enlarge

Another RTFM moment was when I wanted to install the B4i-Bridge app on the device. I started watching the video and forgot to read the bold sentence above it:

Before you install B4i-Bridge you must install the B4I certificate. This step is not shown in the video. Open Safari (device browser) and navigate to: www.b4x.com/ca.pem

Clearly stated, but hey, I was in a hurry…

I first tried the Hosted Builder option to compile the app. Very smooth and a excellent alternative for Windows developers who do not own a Mac. And for $26 a year, a bargain.

But, as I want to experiment with creating libraries myself in Objective-C, I wanted to install the local MacBuildServer. Again, following the tutorial, everything went very well. Downloading XCode took most of the time.

One note: Make sure your Mac is in the same IP range as the rest of your development environment. At first, the Mac had IP while the rest was in the 192.168.1.x range. So it didn’t work.

The rest was pure cosmetic. I added an shortcut on the Mac to start the MacBuildServer, and one on the PC side to shut it down.

Creating the shortcut on the Mac side went like this:

  • Open up a terminal
  • go to the folder where you unzipped the macserver-aa (in my case, it’s on the desktop, so it looked like this:

    $ cd desktop
    $ cd macbuilder-aa

  • create a text file

    $ shout start.command

  • add the following lines (adjust the cd to the path where your MacBuildServer is)

    cd /Users/Alwaysbusy/Desktop/macserver-aa
    java -jar B4iBuildServer.jar

  • save and in the terminal type:

    $ chmod -x start.command

  • Right click on start.command, pic ‘Get Info’ in the menu and rename it to something like ‘B4i Build Server Start.command’.
    Click ‘Hide extension’
  • And change the icon to a nice B4i one. I’ve ripped the B4i icon from the exe (sorry Erel) and saved it as a .png. In case you need it, here it is:
    Open the png on the Mac in preview and copy it (Edit – Copy). In the ‘Info Panel’ of the command file, click on the icon until it gets a blue rectangle. Then you can do ‘Edit – Past’.
    In my case, it looked like this:


Coming from Windows and being used to creating .bat files, this is all rather complicated on a Mac I must say.

On the PC side I created also the icon to shut the MacBuildServer down. Enter http://:51041/kill in your favorite browser. Create a bookmark and drag it to your desktop. Rename it to something like ‘B4i Build Server Kill’. You can also change the icon:

  • Right click on the shortcut and pick ‘Properties’
  • Press ‘change icon’
  • Browse to where you have installed B4i
  • Pick B4i.exe and select the icon

So (besides my shortcut creation problems on a Mac), setting up B4i is a breeze! I’m ready to add some serious iOS programming experience to my portfolio.

Get B4i now for only $59 from the Anywhere Software Store!

Here are some quick links to the tutorial parts I used:
Creating a certificate and provisioning profile
Installing B4i-Bridge and debugging first app
Local Mac Builder Installation

See ya!


Basic4Android: ABSYNCMenu, making an Actionbar with Submenus. Easy!

ABSYNCMenu.bas is a code module for an Actionbar with submenus completely written in Basic4Android. It’s an easy to use module you can drop into any project and with a couple of lines of code you have your own action bar with submenus!

Note: I’m aware there is an excellent actionbar library from corwin42 called AHActionBar at the B4A website, but as this ABSYNCMenu module is part of the upcoming ABSYNC Genesis tool (more on this tool in a later article!), I wanted to share this module with you.

Let’s get started!

Start a new project and import the attached module ABSYNCMenu.bas.

In the Main Activity we will add all the code needed to create and handle the action bar and menu. I’ll only cover the code needed for the actionbar in this tutorial, not the other ‘normal’ B4A code. There are some excellent tutorials in the B4A forum, check them out.

We define tree panels that are needed to build the ABSYNC Menu in the Sub Globals.
ABS_MainMenuPanel: for the transparent background over the whole activity that makes all the rest of the program darker and unclickable.
ABS_ActionBarPanel: for the the actionbar
ABS_DropdownMenuPanel: for the dropdown menu

Sub Globals
    Dim ABS_MainMenuPanel As Panel
    Dim ABS_ActionBarPanel As Panel
    Dim ABS_DropdownMenuPanel As Panel
End Sub

In the Activity_Create sub we load our initial layout file (.bal) we created in the designer. This may just be an empty form. See the project at the end of the article for more info. Then we call our BuildMenu() function where we define our action bar and menus.

Sub Activity_Create(FirstTime As Boolean)
    ' load the initial layout

    ' call the function to initialize our menu
End Sub

Suppose we want to create the following actionbar with submenus:

Notice some menu items need to have an icon and some of them need to be disabled.
I’ll go over every major part in the code of the BuildMenu() function to explain how it works.

Start with the ABSYNC menu definition:

ABSYNCMenu.ABSYNCMenuBegin(ABS_MainMenuPanel, ABS_ActionBarPanel, ABS_DropdownMenuPanel, "ABSYNCMenuEvent", Activity.Width, Activity.Height)

Set some properties, like the colors and height of the action bar:

ABSYNCMenu.ActionBarHeight = 40dip
ABSYNCMenu.ColorActionBar = Colors.ARGB(255,255,0,0)
ABSYNCMenu.ColorActionBarItemEnabled = Colors.ARGB(255,255,255,255)
ABSYNCMenu.ColorActionBarItemDisabled = Colors.ARGB(255,64,64,64)
ABSYNCMenu.ColorMenu = Colors.ARGB(255,255,255,255)
ABSYNCMenu.ColorMenuItemEnabled = Colors.ARGB(255,0,0,0)
ABSYNCMenu.ColorMenuItemDisabled = Colors.ARGB(255,192,192,192)

Important! When you add an actionbar item you can have them left our right aligned. Depending on the alignment the icons are shown in a different order.

If the alignment is LEFT then the order of the shown icons is:
first added, second added, third added, …

If the alignment is RIGHT then the order of the shown icons is:
…, third added, second added, first added

Let’s add a simple item to the taskbar. Every actionbar item has to start with ABSYNCMenu.AddActionBarItemBegin and has to end with ABSYNCMenu.AddActionBarItemEnd. The syntax for the AddActionBarItem is as follows:

Sub AddActionBarItem(ReturnValue As String, bmpEnabled As String, bmpDisabled As String, ItemWidth As Int, LeftAligned As Boolean, Visible As Boolean, Enabled As Boolean, MenuWidth As Int)

ReturnValue: the value that will be returned to the ABSYNCMenuEvent() function. This is also the text that will be shown if no icon is provided.
bmpEnabled: the file name of the bmp for the Enabled icon.
bmpDisabled: the file name of the bmp for the Disabled icon.
ItemWidth: the width of this item. Can be bigger than the icon width. The icon will then be centered withion this width.
LeftAligned: is this icon aligned to the left of your screen or the right. See note above about alignment.
Visible: is this item visible.
Enabled: is this item enabled.
MenuWidth: the total with of the sub menu, if any.

So our full first item is like this:

ABSYNCMenu.AddActionBarItem("Home", "", "", 50dip, True, True, True, 0)

Another example is an actionbar item with an icon and a submenu. right after you added the actionbar item, you can add the submenu with the AddMenuItem() function.
the syntax of AddMenuItem() is:

Sub AddMenuItem(ReturnValue As String, bmpEnabled As String, bmpDisabled As String, ItemHeight As Int, IconWidth As Int, Enabled As Boolean)

ReturnValue: the value that will be returned to the ABSYNCMenuEvent() function. This is also the text that will be shown next to the icon
bmpEnabled: the file name of the bmp for the Enabled icon.
bmpDisabled: the file name of the bmp for the Disabled icon.
ItemHeight: the height of this item.
IconWidth: the width of the iconspace.
Enabled: is this item enabled.

The full item looks like this:

ABSYNCMenu.AddActionBarItem("Menu", "abmenuE.png", "abmenuD.png", 50dip, False, True, True, 160dip)
ABSYNCMenu.AddMenuItem("Register", "", "", 40dip, 30dip, True)
ABSYNCMenu.AddMenuItem("Connections", "ConnectionsE.png", "ConnectionsD.png", 40dip, 0, True)
ABSYNCMenu.AddMenuItem("Tables", "", "", 40dip, 0, False)

After all items are added, end the ABSYNC menu definition and add it to this activity:

ABSYNCMenu.ABSYNCMenuEnd(ABS_ActionBarPanel, ABS_DropdownMenuPanel)
Activity.AddView(ABS_MainMenuPanel, 0,0, Activity.Width, ABSYNCMenu.ActionBarHeight)

Now we can write our function that will handle the menu click event. This function will be automatically called by the ABSYNCMenu module.
This function is straightforward. The comments will explain what happens:

' function that returns if someone clicked on an action bar item or on a sub menu item
' Here is where you do your stuff
Sub ABSYNCMenuEvent(ReturnValue As String, HasMenu As Boolean)
	If HasMenu Then
		' is an action bar item with a menu, open it and return
		ABS_MainMenuPanel.SetLayout(0,0, Activity.Width, Activity.Height)
		' is an action bar item without a menu OR an actual menu item so we have to handle it
		ABS_MainMenuPanel.SetLayout(0,0, Activity.Width, ABSYNCMenu.ActionBarHeight)
		Select Case ReturnValue
			Case "Home"
			Case "Register"
			Case "Connections"
			Case "Tables"
			Case "All tables"
				ToastMessageShow(ReturnValue, False)
			Case "Register tables"
				ToastMessageShow(ReturnValue, False)
		End Select
	End If
        ' and redraw the action bar and menu
	ABSYNCMenu.Draw(ABS_ActionBarPanel, ABS_DropdownMenuPanel)
End Sub

Finally we’ll have to cover the touch events on the tree panels. We’ll send the event to the ABSYNCMenu module an it will handle all the rest for you.

Sub ABS_ActionBarPanel_Touch (Action As Int, X As Float, Y As Float) As Boolean 'Return True to consume the event
	' in the touch event, let the ABSYNCMenu module handle the touch
	Return ABSYNCMenu.DoActionBarTouch(Action, X, Y)
End Sub

Sub ABS_DropdownMenuPanel_Touch (Action As Int, X As Float, Y As Float) As Boolean 'Return True to consume the event
	' in the touch event, let the ABSYNCMenu module handle the touch
	Return ABSYNCMenu.DoMenuTouch(Action, X, Y)
End Sub

Sub ABS_MainMenuPanel_Touch (Action As Int, X As Float, Y As Float) As Boolean 'Return True to consume the event
	' did not touch a menu or action bar item. Close it up!
	ABS_MainMenuPanel.SetLayout(0,0, Activity.Width, ABSYNCMenu.ActionBarHeight)
	Return True
End Sub

Finished! As you can see with some very easy coding we’ll have a fully working actionbar with dropdown menu’s!

Check out the source code with the ABSYNCMenu.bas module here:

Until next time!

Click here to Donation if you like my work

Basic4Android: Using the new 3D Camera in ABExtDrawing 1.1

I’ve added the Camera object to the ABExtDrawing library for Basic4Android. This object must not be confused with the hardware camera. There are other libraries available for that. The new version 1.1 of the library can be downloaded from the B4X website.

The camera I’m talking about is a nice feature you can use to do 3D effects on the canvas without using OpenGL. The picture above is just a noral B4A canvas where we did some rotations and translations on. It simulates a scrolling list where the listitems rotate around their axe.

Additional, I shows other features of the ABExtDrawing library to do some lighting effects.

Let me show you how this is done in B4A.

We create a new type item3D. This will hold one item in the list.

Sub Process_Globals
	Type item3D (bmp As Bitmap, Top As Int, Left As Int, Width As Int, Height As Int)
End Sub

We also have to declare some variables. Note our mCamera variable which will do the 3D conversions and some constants for our lighting effects. On a Paint object we can set color filters which will affect the color values of what we draw with that Paint object. SetLightingColorFilter takes care of that. A LightingColorFilter takes two colors that are used to modify the colors that we are drawing. The first color will be multiplied with the colors we draw, while the second one will be added to the colors we draw. The multiplication will darken the color and adding will make it brighter so we can use this class to model both shadows and highlights. It would have been even better if instead of adding it would have implemented the screen blend mode, but add works OK.

To actually calculate the light we’ll use a simplified version of Phong lighting.

Sub Globals
	'These global variables will be redeclared each time the activity is created.
	'These variables can only be accessed from this module.
	Dim items As List
	Dim HalfHeight As Float


	' Ambient light intensity
    ' Diffuse light intensity
    ' Specular light intensity
    ' Shininess constant
    Dim SHININESS As Float: SHININESS = 200
    ' The Max intensity of the light

	Dim CurrentRotation As Int
	Dim CurrentTop As Int
	Dim MyCanvas As Canvas

	Dim ScreenTop As Int: ScreenTop = 1
	Dim Panel1 As Panel

	Dim ExDraw As ABExtDrawing
	Dim mCamera As ABCamera
	Dim mMatrix As ABMatrix
	Dim mPaint As ABPaint

	Dim PI As Double: PI= 3.141592653589793238462643383279502884197

	Dim ClearRect As Rect

	Dim CurrY As Int
End Sub

In the Activity_Create sub we initialize mCamera and the other variables like mPaint which we will also need for our lighting. Also our pictures are preloaded.

Sub Activity_Create(FirstTime As Boolean)


	HalfHeight = Activity.Height / 2

	Dim backbmp As Bitmap
	backbmp.Initialize(File.DirAssets, "background.png")
	Dim backbmp2 As Bitmap
	backbmp2.Initialize(File.DirAssets, "background2.png")
	Dim backbmp3 As Bitmap
	backbmp3.Initialize(File.DirAssets, "background3.png")

	Dim conbmp As Bitmap
	conbmp.Initialize(File.DirAssets, "contact_image.png")
	Dim conbmp2 As Bitmap
	conbmp2.Initialize(File.DirAssets, "contact_image2.png")
	Dim conbmp3 As Bitmap
	conbmp3.Initialize(File.DirAssets, "contact_image3.png")

	Dim i As Int
	Dim random As Int
	For i = 0 To 19
		random = Rnd(0,3)
		If random = 0 Then
			items.Add(CreateNewItem(backbmp, conbmp, "Colleague " & i, "Name of colleague " & i, 25, i*175, Activity.Width - 50, 120))
			If random = 1 Then
				items.Add(CreateNewItem(backbmp2, conbmp2, "Friend " & i, "Name of friend " & i, 25, i*175, Activity.Width - 50, 120))
				items.Add(CreateNewItem(backbmp3, conbmp3, "Client " & i, "Name of the client " & i, 25, i*175, Activity.Width - 50, 120))
			End If
		End If

	CurrentRotation = -(DEGREES_PER_SCREEN * ScreenTop) / Activity.Height

	ClearRect.Initialize(0,0,Activity.Width, Activity.Height)


End Sub

The sub CreateNewItem() is used to make one list item. Default B4A canvas drawing functions are used to show how well they work together with the ABExtDrawing functions.

Sub CreateNewItem(Background As Bitmap, icon As Bitmap, Subj As String, desc As String, Left As Int, Top As Int, Width As Int, Height As Int) As item3D
	Dim item As item3D
	Dim c As Canvas
	item.bmp.InitializeMutable(Width, Height)


	' background
	Dim dstR As Rect
	c.DrawBitmap(Background,Null, dstR)

	' draw Icon
	dstR.Initialize(15,15, icon.Width, icon.Height)
	c.DrawBitmap(icon, Null, dstR)

	c.DrawText(Subj, 100, 30,Typeface.DEFAULT_BOLD,16, Colors.White,"LEFT")
	c.DrawText(desc, 100, 60, Typeface.DEFAULT,16, Colors.White,"LEFT")

	item.Top = Top
	item.Left = Left
	item.Width = Width
	item.Height = Height
	Return item
End Sub

In the drawItem() sub all calculations are done for one item in the list. Each item will be a block that will rotate around its X-axis and look like it is rolling on the ground when the list stars to scroll. Each block will be as wide as the item normally is and the depth will be the same as the height. We’ll use the same bitmap for all the sides.

So what do we need to do to achieve this effect? In order to draw the blocks we need to draw the bitmap two times (since we will almost always see two sides of the block). We also need to have some kind of rotation variable to keep track of the main rotation. Since the blocks should rotate when the user scrolls the list and the blocks should have the same rotation (so that they all face up at the same time, see further).

Sub DrawItem(item As item3D)
	Dim CenterX As Float
	Dim CenterY As Float

	' get centerX AND centerY
	CenterX = item.Width / 2
	CenterY = item.Height / 2

    ' get scale
    Dim distFromCenter As Float
	distFromCenter = (item.Top + CenterY - HalfHeight) / HalfHeight
	Dim scale As Float
	scale = (1 - SCALE_DOWN_FACTOR * (1 - Cos(distFromCenter)))

    ' get rotation
    Dim RotationX As Float
	RotationX = CurrentRotation - 20 * distFromCenter
    RotationX = RotationX Mod 90
    If (RotationX < 0) Then
        RotationX = RotationX + 90
    End If	

    ' draw it
    If (RotationX < 45) Then
		drawFace(item, CenterX, CenterY, scale, RotationX - 90)
        drawFace(item, CenterX, CenterY, scale, RotationX)

        drawFace(item, CenterX, CenterY, scale, RotationX)
        drawFace(item, CenterX, CenterY, scale, RotationX - 90)
    End If
End Sub

Finally, DrawFace is called and this is where the magic happens. Worth noting is that the code that will draw one face of the block is the same, it just depends on the rotation, so it’s extracted to a method. To draw a complete block we then simply draw two faces 90 degrees apart at the same place.

To draw a face we first translate the camera so that the face will be drawn closer to us. Then we rotate it and after that we translate it back so we don’t scale it. Keep in mind that the calls to the camera, just like the rotate, translate and scale methods on Canvas, needs to be written in reversed order, so to speak. In the code below, it is the last line that translates the face towards us, then we rotate it, and finally, with the first line, we translate it back.

mCamera.translate(0, 0, centerY);
mCamera.translate(0, 0, -centerY);

The rest of drawFace is not that hard. It gets the matrix from the camera, pre and post translates the matrix and then draws the bitmap with the matrix.

This code will draw each item as if placed in the origin in 3D space and then we move the items to the correct place on the screen using pre and post translate on the matrix. This moves what we draw in 2D space without changing the perspective. We could apply the translation in X and Y on the camera instead, then the translation would be in 3D space and it would affect the perspective. We’re not doing that here because I want the appearance of a larger field of view than the fixed field of view of the camera. Instead, we fake it by slightly rotating and scaling the items depending on the distance from center of the screen.

We calculate the light and create a LightingColorFilter that we can set to our Paint object.

Sub drawFace(item As item3D, CenterX As Float, CenterY As Float, scale As Float, RotationX As Float)
	' save the camera state

    ' translate AND Then rotate the camera
    mCamera.translate(0, 0, CenterY)
	mCamera.translate(0, 0, -CenterY)

    ' get the matrix from the camera AND Then restore the camera

    ' translate AND scale the matrix
    mMatrix.preTranslate(-CenterX, -CenterY)
    mMatrix.postScale(scale, scale)
    mMatrix.postTranslate(item.left + CenterX, item.top + CenterY)

    ' set the light
	Dim cosRotation As Double
	cosRotation = Cos(PI * RotationX / 180)
    Dim intensity As Int
	intensity = AMBIENT_LIGHT + (DIFFUSE_LIGHT * cosRotation)
    Dim highlightIntensity As Int
	highlightIntensity = (SPECULAR_LIGHT * Power(cosRotation,SHININESS))
    If (intensity > MAX_INTENSITY) Then
        intensity = MAX_INTENSITY
    End If
    If (highlightIntensity > MAX_INTENSITY) Then
        highlightIntensity = MAX_INTENSITY
    End If
    Dim light As Int
	light = Colors.rgb(intensity, intensity, intensity)
    Dim highlight As Int
	highlight = Colors.rgb(highlightIntensity, highlightIntensity, highlightIntensity)
    mPaint.SetLightingColorFilter(light, highlight)   

    ' draw the Bitmap
    ExDraw.drawBitmap4(MyCanvas, item.bmp,  mMatrix, mPaint)
End Sub

The DrawMe() sub is the overall function to draw all the items.

Sub DrawMe()
	Dim i As Int
	ExDraw.save2(MyCanvas, ExDraw.MATRIX_SAVE_FLAG)
	MyCanvas.DrawRect(ClearRect, Colors.Black, True, 1dip)
	'MyCanvas.DrawBitmap(FormBack, Null, formR)
	For i = 0 To items.Size - 1

End Sub

And in the Panel1_Touch sub we’ll animate our list. Note that it is here that we make sure all boxes face the same. This is done by the lines:

ScreenTop = ScreenTop + DeltaY
CurrentRotation = -(DEGREES_PER_SCREEN * ScreenTop) / Activity.Height

Doing like this will make the blocks rotate DEGREES_PER_SCREEN degrees when the user scrolls the list an entire screen no matter the pixel-height of the screen.

Here is the full sub:

Sub Panel1_Touch (Action As Int, X As Float, Y As Float) As Boolean 'Return True to consume the event
	Dim DeltaY As Int
	Select Action
        Case Activity.ACTION_DOWN
			CurrY = Y
        Case Activity.ACTION_MOVE
			DeltaY = Y - CurrY
			CurrY = Y
			Dim i As Int
			Dim it As item3D
			For i = 0 To items.Size - 1
				it = items.Get(i)
				it.Top = it.Top + DeltaY
				items.Set(i, it)

			ScreenTop = ScreenTop + DeltaY
			CurrentRotation = -(DEGREES_PER_SCREEN * ScreenTop) / Activity.Height

        Case Activity.ACTION_UP
    End Select
    Return True
End Sub

So this concludes this tutorial. You can download the project from http://www.gorgeousapps.com/AB3DCamera.zip

Note that at the first run, it may not work very smooth on some devices. But after some time it goes very well.

Have fun programming and until next time!

Click here to Donation if you like my work

Basic4Android: new library ABExtDrawing

ABExtDrawing is a library I wrote to access more from the Android Drawing classes in B4A. It extends the B4A canvas so you can also use all Paint, Matrix, Region, ColorMatrix and Path functionalities.

Several sub objects are included:
ABPaint: a wrapper for thePaint class
ABMatrix: a wrapper for the Matrix class
ABRegion: a wrapper for the Region class
ABColorMatrix: a wrapper for the ColorMatrix class
ABRgbFunctions: several functions to manipulate RGB values

Also two extended classes
ABRectF: a wrapper around the RectF class. B4A contains the Rect class, but to use some of the functions of this library I needed the float version of Rect.
ABPath: a full wrapper for the Path class. B4A contains the Path class but only exposes LineTo. ABPath exposes all functions (like addArc, addOval, etc…)

This library is to big to list all the functions, but a lot of them are used in the attached demo. It is a B4A translation of the Thermometer project on Mind The Robot http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/

How to use this library:

The main object is ABExtDrawing. You pass the B4A canvas to each function:

Sub Globals
        Dim ExDraw As ABExtDrawing
        Dim MyCanvas As Canvas
        Dim Panel1 as Panel
end Sub

Sub Activity_Create(FirstTime As Boolean)
        If FirstTime Then
	End If
End Sub

Sub drawRim(Canv As Canvas)
	' first, draw the metallic body
	ExDraw.drawOval(Canv, rimRect, rimPaint)
	' now the outer rim circle
	ExDraw.drawOval(Canv, rimRect, rimCirclePaint)
End Sub

The fun part is you can create all kind of Paints:

        ' the linear gradient Is a Bit skewed For realism
	rimPaint.SetLinearGradient2(1,0.40, 0.0, 0.60, 1.0, Colors.RGB(0xf0, 0xf5, 0xf0),Colors.RGB(0x30, 0x31, 0x30),rimPaint.ShaderTileMode_CLAMP)

	rimCirclePaint.SetColor(Colors.ARGB(0x4f, 0x33, 0x36, 0x33))

Or make extended Paths:

	handPath.moveTo(0.5, 0.5 + 0.2)
	handPath.lineTo(0.5 - 0.010, 0.5 + 0.2 - 0.007)
	handPath.lineTo(0.5 - 0.002, 0.5 - 0.32)
	handPath.lineTo(0.5 + 0.002, 0.5 - 0.32)
	handPath.lineTo(0.5 + 0.010, 0.5 + 0.2 - 0.007)
	handPath.lineTo(0.5, 0.5 + 0.2)
	handPath.addCircle(0.5, 0.5, 0.025, handPath.Direction_CW)

You can also use the Save and Restore functions of the canvas:

Sub drawScale(Canv As Canvas)
	ExDraw.drawOval(Canv, scaleRect, ScalePaint)

	ExDraw.save2(Canv, ExDraw.MATRIX_SAVE_FLAG)
	Dim i As Int
	Dim y1 As Float
	Dim y2 As Float
	Dim value As Int
	Dim valueString As String
	For i = 0 To totalNicks
		y1 = scaleRect.top
		y2 = y1 - 0.020

		ExDraw.drawLine(Canv, 0.5, y1, 0.5, y2, ScalePaint)

		If (i Mod 5 = 0) Then
			value = nickToDegree(i)
			If (value &gt;= minDegrees AND value &lt;= maxDegrees) Then
				valueString = value
				ExDraw.drawText(Canv, valueString, 0.5, y2 - 0.015, ScalePaint)
			End If
		End If

		ExDraw.rotate2(Canv, degreesPerNick, 0.5, 0.5)
End Sub

And write filters like this GreyScale filter:

Sub GrayScale(bmp As Bitmap) As Bitmap
    Dim bmpGrayscale As Bitmap
    bmpGrayscale.InitializeMutable(bmp.Width, bmp.height)
    Dim c As Canvas

    Dim paint As ABPaint

    Dim mat As ABColorMatrix


    ExDraw.drawBitmap2(c, bmp, 0, 0, paint)

    Return bmpGrayscale
End Sub

Because of all the possibilities this library has, I may do some more articles on this blog.

For more information on what you can do with the library, look into the Android Documentation http://developer.android.com/reference/android/graphics/Canvas.html

As a registered user, you can download the library from the Basic4Android website
The demo project can be downloaded from http://www.gorgeousapps.com/ABExtDrawingDemo.zip

Click here to Donation if you like my work