Programmatically scrolling a word into view in a textview

前端 未结 1 1117
既然无缘
既然无缘 2020-12-06 08:10

I have TextView with a large amount of text, the user searches for something and I highlight the matches, however they may be way down the page, is there a way to scroll to

相关标签:
1条回答
  • 2020-12-06 08:49

    I'm assuming there's no horizontal scrolling. If there is, you can extrapolate from this answer. Seeing as you're highlighting the matches, I'm also going to assume you have the finding part down already. This means you should have at least a start position for the search string in the CharSequence.

    Use Layout.getLineForOffset to find the line for the string, then Layout.getLineTop to get the position of the top of the line, then View.scrollTo to scroll to your desired position. It should look something like this:

    Layout layout = textView.getLayout();
    scrollView.scrollTo(0, layout.getLineTop(layout.getLineForOffset(startPos)));
    

    I haven't tried this out, so you might have to do something to deal with the padding that you've added, etc. but I would think the general idea should work.

    0 讨论(0)
提交回复
热议问题