Android Code Snippet standard tooltips for Android 8+

For tooltips (press-and-hold on a view to show some explanatory text), in the past I used a hack in my apps to position a toast message near the view. This has stopped working on certain recent versions of Android (I'll cover that in a separate post), so I went looking for a better solution.

It turns out that Android 8 added a proper way to define tooltips (with Android 8+ currently covering more than 90% of devices).

As far as I know, we can't do this yet in B4A natively (aView.tooltip = "bleem"), so here's a sub that uses JavaObject to call that Java method:

B4X:
'in each activity, I use a single sub to add all the tooltips on that screen
Sub addAllTooltips
    setTooltip(saveButton, "Save & done")
    setTooltip(cancelButton, "Cancel")
End Sub

'on Android 8+, attaches a tooltip to the given view.
'Ignored on earlier versions of Android
Sub setTooltip(viewArg As View, textArg As String)
    Dim p As Phone
    If p.SdkVersion >= 26 Then
        Dim viewJO As JavaObject = viewArg
        viewJO.RunMethod("setOnLongClickListener", Array As Object(Null))   'remove any longClick listener
        viewJO.RunMethod("setTooltip", Array As Object(textArg))
    End If
End Sub

Hope this helps!
 
Last edited:

Sandman

Expert
Licensed User
Longtime User
I was wondering what it looked like and found the official documentation, which contains a picture:

1665406046226.png

 

Star-Dust

Expert
Licensed User
Longtime User
Sorry, maybe I don't understand, but what is the difference between this solution is putting a ToastMessage on the LongClick event
 

Dave O

Well-Known Member
Licensed User
Longtime User
Ideally a tooltip is positioned near the view that you long-press, so it's visually associated with that view. But to do this, you need to muck around with the standard toast message, which no longer works in Android 12 (it just displays the toast in its usual center-bottom position), and which can cause crashes on some devices (in my recent experience).

The standard tooltip shown above is smaller than a toast and positioned properly. And it's not as "hacky" as trying to reposition a toast message.

If you want the standard tooltip, and you're OK with it only appearing on Android 8+ (which now means about 90% of devices), this is a better solution.

If you're OK with using a toast that appears in the normal toast location, and that will work on all versions of Android, then the toast might be a better solution for you.
 

stevel05

Expert
Licensed User
Longtime User
If you're using designer script extensions (and why wouldn't you?) there is a DSE version of this code here. @Dave O asked me to post it here so you could choose which version suits you best.
 
Top