Android Code Snippet show toast message at position

Dave O

Active Member
Licensed User
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

Administrator
Staff member
Licensed 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
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.
 
Top