2014-01-10 56 views
3

我擁有大量文本的TextView,用戶搜索某些內容並突出顯示匹配,但它們可能會沿頁面向下,是否有滾動到第一場比賽?在文本視圖中以編程方式將單詞滾動到視圖中

我看着谷歌,似乎沒有發現任何相關的東西。

我的佈局:

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

回答

4

我假設有沒有水平滾動。如果有的話,你可以從這個答案推斷。看到你突出顯示的比賽,我也會認爲你已經找到了一部分。這意味着您至少應該在CharSequence中搜索字符串的起始位置。

使用Layout.getLineForOffset查找字符串的行,然後Layout.getLineTop獲取行的頂部的位置,然後View.scrollTo滾動到您想要的位置。它應該是這個樣子:

Layout layout = textView.getLayout(); 
scrollView.scrollTo(0, layout.getLineTop(layout.getLineForOffset(startPos))); 

我還沒有嘗試過這一點,所以你可能必須做一些事來處理您添加填充等,但我認爲總體思路應工作。

+0

爲我工作!但是我在ScrollView中有很多其他視圖,所以我不得不這樣做:'scrollView.scrollTo(0,layout.getLineTop(txtView.getTop()+ layout.getLineForOffset(startPos)));'so txtView.getTop()以相對於其父視圖的像素爲單位獲取textView的頂部位置,並將其添加到正在查找的行的getLineTop垂直位置 – nommer

+0

因爲我正在尋找一個沒有XML廢話的實用示例 –

相關問題