Android Code Snippet Custom Toast Message

Discussion in 'Code Snippets' started by Erel, Feb 5, 2018.

  1. Erel

    Erel Administrator Staff Member Licensed User

    [​IMG]

    You can customize the toast message text with CSBuilder: https://www.b4x.com/android/forum/threads/76226/#content

    This code allows you to also change the background color and the toast position:
    Code:
    Sub ShowCustomToast(Text As Object, LongDuration As Boolean, BackgroundColor As Int)
       
    Dim ctxt As JavaObject
       ctxt.InitializeContext
       
    Dim duration As Int
       
    If LongDuration Then duration = 1 Else duration = 0
       
    Dim toast As JavaObject
       toast = toast.InitializeStatic(
    "android.widget.Toast").RunMethod("makeText"Array(ctxt, Text, duration))
       
    Dim v As View = toast.RunMethod("getView"Null)
      
    Dim cd As ColorDrawable
      cd.Initialize(BackgroundColor, 
    20dip)
      v.Background = cd
       
    'uncomment to show toast in the center:
    '   toast.RunMethod("setGravity", Array( _
    '       Bit.Or(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_VERTICAL), 0, 0))
       toast.RunMethod("show"Null)
    End Sub
    Depends on JavaObject library

    Usage example:
    Code:
    Sub Activity_Click
       ShowCustomToast(
    "Testing..."TrueColors.Green)
       Sleep(
    3000)
       
    Dim cs As CSBuilder
       cs.Initialize.Color(
    Colors.Blue).Size(20).Append("Custom Toast").PopAll
       ShowCustomToast(cs, 
    TrueColors.Red)
    End Sub
     
    Last edited: Feb 11, 2018
    lemonisdead, arastoo, Beja and 20 others like this.
  2. janderkan

    janderkan Active Member Licensed User

    On my Android 7.1.1 I get a square toast.
    Is it possible to have rounded corners?
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    Try the updated code.
     
    arastoo, Beja and janderkan like this.
  4. Walter Brunmueller

    Walter Brunmueller Member Licensed User

    I had problems to get a toast message.
    Afte hours of testing I found the solution.
    It is necessary to activate notification for your app in the android system.

    I hope this helps.
     
  5. Walter Brunmueller

    Walter Brunmueller Member Licensed User

    One question:

    how can I cancel an activated toast message?
     
  6. Erel

    Erel Administrator Staff Member Licensed User

    The toast disappears automatically after a few seconds.

    You can hide it immediately with:
    Code:
    toast.RunMethod("cancel"Null)
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice