Programmatically scrolling a word into view in a textview

大憨熊 提交于 2020-02-10 03:17:09

问题


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.

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>

回答1:


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.



来源:https://stackoverflow.com/questions/21054528/programmatically-scrolling-a-word-into-view-in-a-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!