Android Code Snippet Custom Toast Message

SS-2018-02-05_09.02.10.png


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:
B4X:
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:
B4X:
Sub Activity_Click
   ShowCustomToast("Testing...", True, Colors.Green)
   Sleep(3000)
   Dim cs As CSBuilder
   cs.Initialize.Color(Colors.Blue).Size(20).Append("Custom Toast").PopAll
   ShowCustomToast(cs, True, Colors.Red)
End Sub
 
Last edited:

janderkan

Well-Known Member
Licensed User
Longtime User
On my Android 7.1.1 I get a square toast.
Is it possible to have rounded corners?
 

Walter Brunmueller

Member
Licensed User
Longtime 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.
 
I used this code, it works well on Android 7, but it gives an error on Android 11:
B4X:
main_showcustomtoast (java line: 409)
java.lang.RuntimeException: Object should first be initialized (View).
    at anywheresoftware.b4a.AbsObjectWrapper.getObject(AbsObjectWrapper.java:67)
    at anywheresoftware.b4a.objects.ViewWrapper.setBackground(ViewWrapper.java:105)
    at com.test.main._showcustomtoast(main.java:409)
    at com.test.main._activity_create(main.java:350)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
    at com.test.main.afterFirstLayout(main.java:105)
    at com.test.main.access$000(main.java:17)
    at com.test.main$WaitForLayout.run(main.java:83)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8550)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
 
Top