以编程方式将单词滚动到文本视图中的视图中 [英] Programmatically scrolling a word into view in a textview

查看:30
本文介绍了以编程方式将单词滚动到文本视图中的视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含大量文本的 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?

我在谷歌上找遍了,似乎没有找到任何相关的东西.

I looked all over google and did not seem to find anything relevant.

我的布局:

<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>

推荐答案

我假设没有水平滚动.如果有,你可以从这个答案中推断出来.当您突出显示匹配项时,我还假设您已经完成了查找部分.这意味着您应该在 CharSequence 中至少有一个搜索字符串的起始位置.

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.

使用 Layout.getLineForOffset 找到字符串所在的行,然后 Layout.getLineTop 获取行首的位置,然后 View.scrollTo 滚动到您想要的位置.它应该看起来像这样:

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.

这篇关于以编程方式将单词滚动到文本视图中的视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆