Highlighting Rows and Text in Scrollview

Bill Norris

Active Member
Licensed User
Longtime User
Have a scrollview with column of labels and each label has one word on it. When determining the width of labels to use on a scrollview, we obviously must make the wide enough to accommodate the longest word that will appear on a label. When we make the code to highlight the row that is touched, it highlights the entire label, by design. What I would like to do is to highlight the text only, meaning if a word is only a few characters long, it won't highlight the entire row. This is purely for appearance, cause it just looks a bit wacky to have a whole row highlighted with just a short word in the middle.
 

klaus

Expert
Licensed User
Longtime User
In the attached sample program you find the principle.
It uses a canvas to draw on a Bitmap of a BitmapDrawable and sets this one to the Label.BackGround.
B4X:
Sub Process_Globals
    Dim ColBackground As Int         : ColBackground = Colors.RGB(255,230,130)
    Dim ColSelected As Int            : ColSelected = Colors.RGB(255,200,200)
End Sub

Sub Globals
    Dim SelectedLabel, Label1, Label2, Label3 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("main")
End Sub

Sub Activity_Resume
    ' initializes the backgrounds
    SetBackground(Label2)
    SetBackground(Label3)
    SetSelected(Label1)
End Sub

Sub Label_Click
    SetBackground(SelectedLabel)
    Dim lbl As Label
    lbl = Sender
    SetSelected(lbl)
End Sub

Sub SetBackground(lbl As Label)
    ' draws the background
    Dim cvs As Canvas
    Dim bmp As Bitmap
    Dim bmd As BitmapDrawable
    Dim rc As Rect
    rc.Initialize(0, 0, lbl.Width, lbl.Height)
    bmp.InitializeMutable(lbl.Width, lbl.Height)
    bmd.Initialize(bmp)
    cvs.Initialize2(bmp)
    cvs.DrawRect(rc, ColBackground, True, 1)
    lbl.Background = bmd
End Sub

Sub SetSelected(lbl As Label)
    ' draws the background
    Dim cvs As Canvas
    Dim bmp As Bitmap
    Dim bmd As BitmapDrawable
    Dim rc As Rect
    rc.Initialize(0, 0, lbl.Width, lbl.Height)
    bmp.InitializeMutable(lbl.Width, lbl.Height)
    bmd.Initialize(bmp)
    cvs.Initialize2(bmp)
    cvs.DrawRect(rc, ColBackground, True, 1)

    ' draws text background with the select color
    Dim xt, x1, x2 As Int
    xt = cvs.MeasureStringWidth(lbl.Text, lbl.Typeface, lbl.TextSize) + 4dip
    x1 = (lbl.Width - xt) / 2
    x2 = x1 + xt
    rc.Initialize(x1, 0, x2, lbl.Height)
    cvs.DrawRect(rc, ColSelected, True, 1)
    
    lbl.Background = bmd
    SelectedLabel = lbl
End Sub
Best regards.
 

Attachments

  • LabelHighlight.zip
    6.6 KB · Views: 195
Upvote 0
Top