Android Code Snippet show toast message at position

With ToastMessageShow, the toast is limited to the bottom center of the screen.

To show a standard Android toast message at a certain position on the screen, use this code instead:

B4X:
'Show standard toast at given x/y position relative to activity.
'Toast will always appear within the screen boundaries, even if x or y is off-screen.
Sub showToastAt(x As Int, y As Int, text As String, longDuration As Boolean)
    Dim duration As Int
    If longDuration = True Then
        duration = 1
    Else
        duration = 0
    End If
    Dim r As Reflector
    r.Target = r.GetActivity
    Dim toastJO As JavaObject
    toastJO.InitializeStatic("android.widget.Toast")
    Dim toastJO2 As JavaObject
    toastJO2 = toastJO.RunMethod("makeText", Array As Object(r.GetContext, text, duration))
    toastJO2.RunMethod("setGravity", Array As Object (Bit.Or(Gravity.TOP, Gravity.LEFT), x, y))
    toastJO2.RunMethod("show", Null)
End Sub

Pros of this approach:
- Simple to use.
- Uses standard Android toast message and visuals.
- Only requires the Reflector and JavaObject libraries included with B4A.
- Does not require a custom-toast library.
- You can extend this code using JavaObject calls to adjust more toast properties.

Cons:
- No fancy formatting, colors, icons, buttons, etc.

Happy coding!
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Similar implementation without Reflection library:
Should be placed in an Activity module.
B4X:
Sub ShowToastAt(x As Int, y As Int, text As String, longDuration As Boolean)
  Dim duration As Int
  If longDuration = True Then
  duration = 1
  Else
  duration = 0
  End If
   Dim ctxt As JavaObject
   ctxt.InitializeContext
  Dim toastJO As JavaObject
  toastJO = toastJO.InitializeStatic("android.widget.Toast").RunMethod("makeText", Array(ctxt, text, duration))
  toastJO.RunMethod("setGravity", Array(Bit.Or(Gravity.TOP, Gravity.LEFT), x, y))
  toastJO.RunMethod("show", Null)
End Sub
 

Gerrard

Member
Licensed User
Longtime User
Is there a way to make the "duration" longer?
In the examples above, if longDuration is True or False, the toast message only lasts about 3 seconds.
 

DonManfred

Expert
Licensed User
Longtime User
Is there a way to make the "duration" longer?
No. That´s how the Toasts under Android works.

Anyway you can use an alternative library to do this. Search the forum; there are some libs which shows custom dialogs... But that are not toasts.
 

PhilN

Member
Licensed User
Longtime User
Thanks for this. Just a point of note for anyone else. To center the toast message: set x = 0 and change Gravity.LEFT to Gravity.CENTER_HORIZONTAL. This worked for me.
 

juanjo.miracle

New Member
Licensed User
Longtime User
On a B4A project it works very well, but when I tried to use on a B4XPage it's shown on bottom center of the screen.
It doesn't matter if you put it on Main Activity or on B4XPage, I get same result.
 
Top