#Region Project Attributes
#ApplicationLabel: Trim String Width Example
#VersionCode: 1
#VersionName:
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#End Region
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
End Sub
Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
End Sub
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.Initialize("Main")
' The long string which is going to be truncated 100 times
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."
' Scrollview containing 100 truncated labels
Dim sv As ScrollView
sv.Initialize(Activity.Height)
Activity.AddView(sv, 0, 0, 100%x, 100%y)
Dim svPanel As Panel
svPanel = sv.Panel
' Create 1,000 truncated labels
Dim x, listBottom As Int
listBottom = 0
For x = 0 To 1000
Dim lbl As Label
lbl.Initialize("lbl")
lbl.Tag = "lbl_" & x
lbl.TextSize = 14
svPanel.AddView(lbl, 0, listBottom, svPanel.Width, 40)
lbl.Text = TrimWidth(LongString, Typeface.DEFAULT, lbl.TextSize, lbl.Width-30dip)
listBottom = lbl.Top + 40dip
Next
sv.Panel.Height = listBottom
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub TrimWidth(Text As String, Style As Typeface, Size As Int, MaxWidth As Int) As String
Return Text
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