Android Code Snippet show toast message at position

Discussion in 'Code Snippets' started by Dave O, Jul 5, 2016.

  1. Dave O

    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:

    Code:
    '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!
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    Similar implementation without Reflection library:
    Should be placed in an Activity module.
    Code:
    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
     
  3. Gerrard

    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.
     
  4. DonManfred

    DonManfred Expert Licensed User

    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.
     
    Peter Simpson likes this.
Loading...