Android Example Scrollview: Adding labels and setting their height automatically depending on the text(size)

This is just a simple example (and yes, there are others doing similar). You can modify this example it by using other colors, gradients, adding other views and so on to have a simple but good looking GUI. Have fun!

- ad a scrollview
- adding x labels to that scrollview (exactly: to the scrollview's panel)
- generate some random sentence with x words
- add these sentence to the label
- set the label's height automatically depending on the textsize
- update the scrollview's height

Please add STRINGUTILS (via libs tab)

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")
    Dim su As StringUtils
    Dim PrevLabelTop, PrevLabelHeight, Spacing, TextSize, NumberOfEntries As Int
   
    Spacing=3dip 'space between the labels
    TextSize=20 'wanted textsize
    NumberOfEntries=50 'how many entries/labels to add to the scrollview
   
    SV.Initialize(1000dip)
    Activity.AddView(SV,0,0,100%x,100%y)
    For i = 0 To NumberOfEntries-1
        Dim MyLabel As Label 'just dim the label
        MyLabel.Initialize("MyLabel") 'initialize it
        SV.Panel.AddView(MyLabel,1%x,PrevLabelTop+PrevLabelHeight+Spacing,98%x,20dip) 'add it to the SV's panel (measuring only works if it's added yet!)
        MyLabel.Text="#" & (i+1) & ": " & GetSentence 'Set the text with some random words
        MyLabel.TextSize=TextSize
        MyLabel.TextColor=Colors.Black
        MyLabel.Color=Colors.white
        MyLabel.height=su.MeasureMultilineTextHeight(MyLabel,MyLabel.Text) 'measure the HEIGHT depending on the textsize and length
        PrevLabelTop=MyLabel.Top 'remeber the top for the next label
        PrevLabelHeight=MyLabel.Height 'remember the height for the next label
    Next
    SV.Panel.Height=PrevLabelTop+PrevLabelHeight+Spacing 'set the new panel's height
End Sub

Sub GetSentence As String 'here we generate a random "sentence" with n words
   
    Dim Sentence As String
    Dim WordCount As Int = Rnd(3,51) 'how many words? Here 3 - 50
   
    Sentence=WordCount & " words... "
   
    For i=0 To WordCount-1
        For l=0 To Rnd(3,10) ' Word length
            Sentence=Sentence & Chr(Rnd(97,122)) 'letters a-z
        Next
        Sentence=Sentence&" "
       
    Next
    Return Sentence
   
End Sub
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…