Android Question Length of a label content in customlistview

kohle

Active Member
Licensed User
Longtime User
Hi,

I want to show only the first line of characters which fit on the screen, depending on different devices
and resolutions. A label has no wrap = false function, so I try to calculate the
number of characters which could be shown.
On 2 devices it work, and on the third not. I get more characters, so a second line.


Sub CreateListItem(Line1 As String,Line2 As String, Width As Int, Height As Int) As Panel

Dim p As Panel
Dim X As Int
Dim W As Int

....

'A long line
' 320x480 : 950646048906845906 459068450964
' 480 x ... : 950646048906845906 459068450964590690469 05946459068540964 054
'
line2 = "950646048906845906 459068450964590690469 05946459068540964 05469054690..."

....
X = C.MeasureStringWidth(Line2, Typeface.DEFAULT, 12)
W = Width-15dip


If W < X Then
X = W / (X / Line2.Length)
Line2=Line2.SubString2(0, X)
End If

'Adding to a customlistview
p.AddView(lbl2, 15dip, 22dip, Width - 15dip, Height - 12dip) 'view #0
....
 

RandomCoder

Well-Known Member
Licensed User
Longtime User
Attached is a little function I've knocked together which hopefully achieves what you want or should at least give some idea of how it can be accomplished. You may want to shorten the string to the nearest full word, i.e. whitespace which could easily be achieved with a small addition to the Do Until loop. I've also had to subtract 30dip from the width of the label for this to work correctly, I can only assume that this is due to the padding within the label?

B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    Activity.LoadLayout("Main")
    Dim LongString As String
    LongString = "This very long line of text needs to be truncated to the width of the label regardless of which font type is used."
    lbl1.Text = LongString
    lbl2.Text = TrimWidth(lbl1.Text, lbl1.Typeface, lbl1.TextSize, lbl1.Width-30dip)
    lbl3.Text = LongString
    lbl4.Text = TrimWidth(lbl3.Text, lbl3.Typeface, lbl3.TextSize, lbl3.Width-30dip)
End Sub

Sub TrimWidth(Text As String, Style As Typeface, Size As Int, MaxWidth As Int) As String
    Dim c As Canvas
    Dim width As Int
    c.Initialize(Activity)
    width = c.MeasureStringWidth(Text, Style, Size)
    If width >= MaxWidth Then
        Do Until width < MaxWidth
            Text = Text.SubString2(0, Text.Length - 1)
            width = c.MeasureStringWidth(Text, Style, Size)
        Loop
        Return Text
    Else
        Return Text
    End If
End Sub

Kind regards,
RandomCoder
 

Attachments

  • TrimStringWidth.zip
    7.2 KB · Views: 163
Upvote 0
Top