Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...