1. Black Friday Sale - 50% off

    B4A Standard for $29 instead of $59!
    Buy Now
    Dismiss Notice

Android Code Snippet Ellipsize Alternative

Discussion in 'Code Snippets' started by Computersmith64, Jan 2, 2019.

  1. Computersmith64

    Computersmith64 Well-Known Member Licensed User

    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.

    Code:
    Public Sub getTruncatedString(sText As String, fFontSize As Float, iconWidth As Int, activity As ActivityAs 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 - 1Then
                
    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.
     
    nanjidusan, Douglas Farias and JohnC like this.
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