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