[英]Programmatically scrolling a word into view in a textview
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 the first match?我有包含大量文本的 TextView,用户搜索某些内容并突出显示匹配项,但是它们可能位于页面下方,有没有办法滚动到第一个匹配项?
I looked all over google and did not seem to find anything relevant.我查遍了谷歌,似乎没有找到任何相关的东西。
My Layout :我的布局:
<ScrollView android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:requiresFadingEdge="vertical"
android:id="@+id/sclView">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtView"
android:textSize="16sp"
android:paddingTop="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:lineSpacingExtra="5dp"
android:textColor="@color/TextGray"
android:textIsSelectable="true"/>
</ScrollView>
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
.这意味着您应该至少有一个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.使用Layout.getLineForOffset
查找字符串的行,然后使用Layout.getLineTop
获取行顶部的位置,然后使用View.scrollTo
滚动到您想要的位置。 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.我还没有尝试过这个,所以你可能需要做一些事情来处理你添加的填充等,但我认为一般的想法应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.