2011-03-13 78 views
2

我想滾動我的TextView以在文本中顯示特定的位置。我怎樣才能做到這一點?我嘗試了bringPointIntoView(int offset),但沒有成功。將TextView滾動到文本位置

的源代碼:

public class TextScrollActivity extends Activity { 
    public void onCreate (final Bundle savedInstanceState) { 
    super.onCreate (savedInstanceState); 
    final int position = 500; 
    final TextView textView = new TextView (this); 
    final ScrollView scrollView = new ScrollView (this); 
    scrollView.addView (textView); 
    Button button = new Button (this); 
    button.setText ("Scroll to " + position); 
    LinearLayout layout = new LinearLayout (this); 
    layout.setOrientation (LinearLayout.VERTICAL); 
    layout.addView (scrollView, 
    new LayoutParams (LayoutParams.FILL_PARENT, 200)); 
    layout.addView (button, new LayoutParams (LayoutParams.FILL_PARENT, 
    LayoutParams.WRAP_CONTENT)); 
    StringBuilder builder = new StringBuilder(); 
    for (int i = 0; i < 1000; i++) 
     builder.append (String.format ("[ %05d ] ", i)); 
    textView.setText (builder); 
    setContentView (layout); 
    button.setOnClickListener (new OnClickListener() { 
     public void onClick (View v) { 
     System.out.println (textView.bringPointIntoView (position * 10)); 
     // scrollView.scrollTo (0, position * 10); // no 
     } 
    }); 
    } 
} 
+0

如果我刪除ScrollView,方法'bringPointIntoView'似乎工作,但現在我無法滾動我的TextView ...我該如何解決這個問題? – Patrick

回答

3

對於那些誰有同樣的問題,我終於做出我自己的實現bringPointIntoView的:

public static void bringPointIntoView (TextView textView, 
    ScrollView scrollView, int offset) 
    { 
    int line = textView.getLayout().getLineForOffset (offset); 
    int y = (int) ((line + 0.5) * textView.getLineHeight()); 
    scrollView.smoothScrollTo (0, y - scrollView.getHeight()/2); 
    } 

,如果你有更好的解決辦法,不要猶豫。

1

向文本視圖添加移動方法是否解決問題?

textView.setMovementMethod(new ScrollingMovementMethod()); 
+0

只有部分原因,因爲有重繪問題,沒有投擲動畫,也沒有滾動條。不管怎麼說,還是要謝謝你 :) – Patrick

1

僅供參考其他任何人有同樣的問題,在listViewlistItems,重載bringPointIntoView可以傳遞一個ListView而不是ScrollView,並使用ScrollTo方法,而不是smoothScrollTo