Android Code Snippet Ellipsize Alternative

Call me slow, but I just noticed the Ellipsize property on Labels & thought "yay - I can replace my hand-written truncation code" - but no, I quickly found out that Ellipsize doesn't work on ListView Labels...

So - I could switch to a CustomListView, but I'm lazy....

Instead, I thought I'd share the code I've been using for a long time to truncate text in the many ListViews I use in myPets. The code is sitting in my AppUtils code module & gets called from various places in the app.

B4X:
Public Sub getTruncatedString(sText As String, fFontSize As Float, iconWidth As Int, activity As Activity) As String
    Private sRetString As String
    Private cvsText As Canvas
    Private fMaxLen As Float
    Private fStringLen As Float
   
    cvsText.Initialize(activity)
    If cvsText.MeasureStringWidth(sText, Typeface.DEFAULT, fFontSize) <= (activity.Width - iconWidth) Then Return sText
    fMaxLen = activity.Width - cvsText.MeasureStringWidth("ZZZ", Typeface.DEFAULT, fFontSize) - iconWidth
    For iCnt = 0 To sText.Length - 1
        sRetString = sText.SubString2(0, iCnt)
        fStringLen = cvsText.MeasureStringWidth(sRetString, Typeface.DEFAULT, fFontSize)
        If fStringLen >= fMaxLen Or (fStringLen = activity.Width And iCnt = sText.Length - 1) Then
            Exit
        End If
    Next
    If iCnt < sText.Length - 1 Then sRetString = $"${sRetString}..."$
    Return sRetString
End Sub

Like I said, this is an old piece of code & could probably be written a lot more efficiently - but it works...

- Colin.
 
Top