Android Question [SOLVED] Find word in long text and position scrollview


Active Member
Licensed User
Longtime User
Based on post #14 in this thread I created a simple application, just to show a long scrollable text.
Now I need to find a word within the text and position the view on that word.
Could anyone help?

The hole "project" is below and the long text (not that long, just to help...) is attached:

Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private scvText As ScrollView
    Private lblText As Label
'    Dim Times, Lucinda As Typeface
    Dim obj1 As Reflector
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1

'    Times=Typeface.LoadFromAssets("times.ttf")
'    Lucinda=Typeface.LoadFromAssets("LHANDW.ttf")
'    lblText.Typeface=Lucinda

    obj1.Target = scvText ' a ScrollView
    Dim args(3) As Object
    args(0) = lblText
    args(1) = -1
    args(2) = -2
    Dim types(3) As String
    types(0) = "android.view.View"
    types(1) = ""
    types(2) = ""
    obj1.RunMethod4("addView", args, types)

    ' search text?
    Dim position As Int = 0 ' = search text...
    scvText.ScrollPosition =  position

End Sub


  • longtext.txt
    3.4 KB · Views: 140


Active Member
Licensed User
Longtime User
I would have used StringUtils.MeasureMultilineTextHeight instead of the reflection code.
You can also use it to find the place of a specific word by measuring the string up to the relevant word.

If anyone else gets here, this is the solution, based on Erel's advice:

    Root.LoadLayout("longtext")    ' just a scrollview
    scvText.Panel.LoadLayout("painel")    ' just a label
    lblTexto.Text = File.GetText(File.DirAssets, "longtext.txt")    

    Dim su As StringUtils

    lblTexto.Height = su.MeasureMultilineTextHeight(lblTexto, lblTexto.Text)

    Dim pos As Int = lblTexto.Text.IndexOf("whatyouwanttofind")
    Dim s As String = lblTexto.Text.SubString2(0, pos)    ' text from the beginning to the word we want
    scvText.ScrollPosition = su.MeasureMultilineTextHeight(lblTexto, s)-20    ' adjust the -20 to your taste

Thank you, Erel.
Upvote 0